Linq list of lists to single list

2020-01-25 04:56发布

Seems like this is the kind of thing that would have already been answered but I'm unable to find it.

My question is pretty simple, how can I do this in one statement so that instead of having to new the empty list and then aggregate in the next line, that I can have a single linq statement that outputs my final list. details is a list of items that each contain a list of residences, I just want all of the residences in a flat list.

var residences = new List<DAL.AppForm_Residences>();
details.Select(d => d.AppForm_Residences).ToList().ForEach(d => residences.AddRange(d));

标签: c# linq
4条回答
闹够了就滚
2楼-- · 2020-01-25 05:10

You want to use the SelectMany extension method.

var residences = details.SelectMany(d => d.AppForm_Residences).ToList();
查看更多
▲ chillily
3楼-- · 2020-01-25 05:17

And for those that want the query expression syntax: you use two from statements

var residences = (from d in details from a in d.AppForm_Residences select a).ToList();
查看更多
狗以群分
4楼-- · 2020-01-25 05:20

Use SelectMany

var all = residences.SelectMany(x => x.AppForm_Residences);
查看更多
不美不萌又怎样
5楼-- · 2020-01-25 05:26

There is a sample code for you:

    List<List<int>> l = new List<List<int>>();

    List<int> a = new List<int>();
    a.Add(1);
    a.Add(2);
    a.Add(3);
    a.Add(4);
    a.Add(5);
    a.Add(6);
    List<int> b = new List<int>();
    b.Add(11);
    b.Add(12);
    b.Add(13);
    b.Add(14);
    b.Add(15);
    b.Add(16);

    l.Add(a);
    l.Add(b);

    var r = l.SelectMany(d => d).ToList();
    foreach(int i in r)
    {
        Console.WriteLine(i);
    }

And the out put will be:

1
2
3
4
5
6
11
12
13
14
15
16
Press any key to continue . . .
查看更多
登录 后发表回答