2

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?

1
  • LINQ also iterates, it just doesn't show in your code. Commented Feb 12, 2014 at 11:23

2 Answers 2

3

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 });
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.