V.B
V.B

Reputation: 1211

Selection from List of tuple to List of objects C#

In my C# code I have a list List<Tuple<int,string>>. I want to select/convert this to a List<Type>. I want to avoid iterating my list of tuple and insert in other list. Is there any way to do this? Maybe with LINQ?

Upvotes: 2

Views: 6183

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

You cannot change type of list. You only can create new list of another type and fill it with converted values from your list. I suggest to use List<T>.ConvertAll method which exists exactly for this purpose:

List<Tuple<int, string>> tuples = new List<Tuple<int, string>>();
// ...
List<YourType> types =
     tuples.ConvertAll(t => new YourType { Foo = t.Item1, Bar = t.Item2 });

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460098

You haven't shown this type, but i assume that it contains an int- and a string-property:

List<MyType> result = tupleList
    .Select(t => new MyType { IntProperty = t.Item1, StringProperty = t.Item2 })
    .ToList();

another option: List.ConvertAll:

List<MyType> result = tupleList.ConvertAll(t => new MyType { IntProperty = t.Item1, StringProperty = t.Item2 });

This presumes that your List<Type> is actually a List<CustomType> (I've called it MyType).

I want to avoid iterating my list of tuple and insert in other list.

LINQ does not avoid loops, it hides them just.

Upvotes: 1

Related Questions