开发者

How to get all elements out of multiple List<>?

In C#, I have the following types:

List<List<mytype>> MyLists;
List<mytype> MainList;

I would like to take each element in all List<> inside MyList and put them in MainList. MainList will then have only elements composed of all elements that were inside each List<> of MyList. I've tried the following but get an er开发者_如何学运维ror about not being able to infer the type:

MyLists.ForEach(list => MainList.AddRange(list.SelectMany(x => x != null)));

I wasn't sure what to put in SelectMany() since I want all elements within the List<>. Those elements don't need to meet any criteria.

Any suggestions how it can be done?


MainList.AddRange(from list in MyLists
                  from element in list
                  select element);

Or, if you prefer,

MainList.AddRange(MyLists.SelectMany(list => list));


This just requires a single SelectMany call:

MainList = MyLists.SelectMany(l => l).ToList();

Note that this doesn't require constructing/initializing MainList prior to this call, as it's completely initialized from the ToList() call.


Edit:

Since you did include a null check, if you need to remove null elements from within your list, you could add that check, as well:

MainList = MyLists.SelectMany(l => l.Where(i => i != null)).ToList();

And/Or filter for entire null lists:

MainList = MyLists
             .Where(l => l != null)
             .SelectMany(l => l.Where(i => i != null))
             .ToList();

Also, if you want to add items to your MainList, as opposed to making MainList "have only elements" in the original lists, you could use AddRange still:

MainList.AddRange(MyLists.SelectMany(l => l));


Another option, closer to your original attempt: MyLists.ForEach(list => MainList.AddRange(list));

In other words, you don't need SelectMany or even Select if you are using ForEach and AddRange.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜