Reputation: 727
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!
Upvotes: 1
Views: 117
Reputation: 24385
You can use some Linq extensions to help you out with the format a bit
var joined = GetList1()
.Concat(GetList2())
.Concat(GetList3().RunFilter())
...
;
Upvotes: 2
Reputation: 53958
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();
Upvotes: 2