本文介绍了展平一个列表,其属性之一是另一个对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public class Owner
{
    public string Id { get; set; }
    public string Name { get; set; }
}
public class Main
{
    public string Id { get; set; }
    public string Name { get; set; }
    public List<Owner> Owners { get; set; }
}

我想将List<Main>转换为FlatList所在的List<FlatList>

I want to convert List<Main> to List<FlatList> where FlatList is

public class FlatList
{
        public string Id { get; set; }          // Id from Main
        public string Name { get; set; }        // Name from Main
        public string OwnerId { get; set; }     // Id from each Owner in a Main's Owner
        public string OwnerName { get; set; }   // Name from each Owner in a Main's Owner
}

不幸的是,我无法找出LinQ查询来执行此操作.

Unfortunately I haven't been able to figure out the LinQ query to perform this operation.

推荐答案

您应使用 SelectMany 将一系列Main对象展平:

You should use SelectMany to flatten a sequence of Main objects:

因此它将每个Main对象投影到FlatList个对象的序列中,然后将得到的序列展平为一个FlatList个序列

So it projects each Main object into sequence of FlatList objects and then flattens resulting sequences into one FlatList sequence

var flatList = mainList.SelectMany(m =>
    m.Owners.Select(o =>
        new FlatList {
              Id = m.Id,
              Name = m.Name,
              OwnerId = o.Id,
              OwnerName = o.Name
         })).ToList()

这篇关于展平一个列表,其属性之一是另一个对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:47