Guillaume Slashy
Guillaume Slashy

Reputation: 3624

Merge List<T> of the same Type

I got 2 Lists whose defs are :

List<Type> filteredTypes = new List<Type>();
List<Type> interfaceTypes = new List<Type>();

When my Lists are populated I'd like to get a single loop on both of them and my idea is to merge them before "looping" so I don't have to use a LINQ (don't like it...-_-) I checked the online doc and I think I gotta do :

filteredTypes.Concat(interfaceTypes);

I debugged as deeply as I could and my Lists are the same after the instruction... What am I missing ?

Upvotes: 4

Views: 6913

Answers (6)

Alok
Alok

Reputation: 1

You have to do :

var temp = firstList.Concat(secondList);
List<Type> finalList = temp.ToList<Type>();

Upvotes: 0

Andrey Sergeev
Andrey Sergeev

Reputation: 1

IEnumerable<T>.Concat(IEnumerable<T>) returns IEnumerable<T>.

Try this:

var resultTypes = filteredTypes.Concat(interfaceTypes);

Upvotes: 0

Wayne Tanner
Wayne Tanner

Reputation: 1356

Why not use AddRange?

 filteredTypes.AddRange(interfaceTypes);

Upvotes: 0

DaveShaw
DaveShaw

Reputation: 52808

The concat function returns a new collection, it doesn't add to the existing one.

var allTypes = filteredTypes.Concat(interfaceTypes);

Upvotes: 7

Andrew Rasmussen
Andrew Rasmussen

Reputation: 15109

Concat returns a new list without modifying either of the original lists. If you want to put it in a new list do this:

List<Type> newList = filteredTypes.Concat(interfaceTypes);

If you want to put it in one of the old lists, use AddRange:

filteredTypes.AddRange(interfaceTypes);

Upvotes: 3

AllenG
AllenG

Reputation: 8190

See here: .NET List<T> Concat vs AddRange

the .Concat() call creates a new List<T> so you'll need something like:

var mergedList = filteredTypes.Concat(interfaceTypes);

Upvotes: 4

Related Questions