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

前端 未结 3 477
南笙
南笙 2021-01-19 19:26

I have the following classes:

public class Owner
{
    public string Id { get; set; }
    public string Name { get; set; }
}
public class Main
{
    public s         


        
相关标签:
3条回答
  • 2021-01-19 20:19
    List<Main> mainList = ...
    var flatList = (
        from main in mainList
        from owner in main.Owners
        select new FlatList {
            Id = main.Id, Name = main.Name,
            OwnerId = owner.Id, OwnerName = owner.Name
        }).ToList();
    
    0 讨论(0)
  • 2021-01-19 20:21

    You can do that using linq (secret looping behind the scenes):

    from m in mainList
    from o in m.Owners
    select new FlatList
    {
       Id  = m.Id,
       Name = m.Name,
       OwnerId = o.OwnerId ,
       OwnerName = o.OwnerName 
    };
    
    0 讨论(0)
  • 2021-01-19 20:22

    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()
    
    0 讨论(0)
提交回复
热议问题