Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a list which one of its properties is another list of object

Tags:

c#

linq

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.

like image 616
user3021830 Avatar asked Dec 24 '22 16:12

user3021830


1 Answers

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()
like image 148
Sergey Berezovskiy Avatar answered Jan 04 '23 22:01

Sergey Berezovskiy