Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c# - Flatten a list which one of its properties is another list of object

I have the following classes:

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; }
}

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
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...