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?
-
LINQ also iterates, it just doesn't show in your code.C.Evenhuis– C.Evenhuis2014-02-12 11:23:04 +00:00Commented Feb 12, 2014 at 11:23
Add a comment
|
2 Answers
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 });
Comments
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.