Reputation: 18743
I have a List
of MyType1
objects. I want to copy all these objects in a new List
of MyType2
objects, having a constructor for MyType2
that takes a MyType1
object as argument.
For now, I do it this way:
List<MyType1> type1objects = new List<MyType1>();
// Fill type1objects
// ...
List<MyType2> type2objects = new List<MyType2>();
foreach (MyType1 type1obj in type1objects) {
MyType2 type2obj = new MyType2(type1obj);
type2objects.Add(type2obj);
}
Is there a way to do this one-line (I'm thinking maybe it is possible with Linq)?
Upvotes: 3
Views: 152
Reputation: 46047
You should be able to do something like this:
List<MyType2> list2 = new List<MyType2>(list1.Select(x => new MyType2(x)));
Upvotes: 0
Reputation: 111870
List<MyType2> type2objects = new List<MyType2>();
type2objects.AddRange(type1objects.Select(p => new MyType2(p)));
In this way you can even preserve the values contained in type2objects
.
I'll add that you know the size of type1objects
, so you can speedup a little:
List<MyType2> type2objects = new List<MyType2>(type1objects.Count);
Here the capacity of type2objects
is pre-setted.
or, if you are re-using an "old2" type2objects
if (type2objects.Capacity < type1objects.Count + type2objects.Count)
{
type2objects.Capacity = type1objects.Count + type2objects.Count;
}
In this way you know the List
won't need intermediate resizes.
Someone will call this premature optimization, and it is. But you could need it.
Upvotes: 0
Reputation:
You might also get some mileage out of Convert.ChangeType() depending on what you're converting:
List<MyType2> type2objects = type1objects.Select(
type1object => Convert.ChangeType(type1object, typeof(MyType2))
).ToList();
Upvotes: 0
Reputation: 12458
If you just copy all elements from list1 to list2 you will not get true copies of those elements. You will just have another list with the same elements!!!
Upvotes: 0
Reputation: 5113
var type2objects = type1objects.Select(type1obj => new MyType2(type1obj)).ToList();
Upvotes: 1
Reputation: 160912
You can use a simple projection using Select()
with Linq, then make a list out of this enumeration using ToList()
:
var type2objects = type1objects.Select( x => new MyType2(x))
.ToList();
Upvotes: 3
Reputation: 10211
var type2objects = type1objects.Select(o => new MyType2(o)).ToList();
Upvotes: 7