简体   繁体   中英

Add mutliple Lists to one list

I have multiple functions that returns a List of objects. How can I add them into one list.

var List1 = GetList1().RunFilter1();
var List2 = GetList2();

The AddRange() function gets far to messy.

List1.AddRange(List2.AddRange(List3.AddRange(List4.AddRange(...); 

Is there a pattern that I can use that it will be easier. I also have extension methods (Filters) that apply to certain lists. Which I interchange based on requirement. Something like this:

var CombinedList = GetAllLists(GetList1().RunFilter1(),
                               GetList2(),
                               GetList3().RunFilter2(),
                               GetList4() ...);

Keep in mind that the GetList() functions being fetched might change.

Thanks for any help!

You could first insert all your lists into another list:

var temp = new List<T>
{
    GetList1().RunFilter1(),
    GetList2(),
    GetList3().RunFilter2(),
    GetList4() 
};

Then using the SelectMany method flatten this list.

var combined = temp.SelectMany(item=>item).ToList();

You can use some Linq extensions to help you out with the format a bit

var joined = GetList1()
    .Concat(GetList2())
    .Concat(GetList3().RunFilter())
    ...
    ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM