Ewald
Ewald

Reputation: 727

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!

Upvotes: 1

Views: 117

Answers (2)

DLeh
DLeh

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

Christos
Christos

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

Related Questions