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)?
var type2objects = type1objects.Select(o => new MyType2(o)).ToList();
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();
var type2objects = type1objects.Select(type1obj => new MyType2(type1obj)).ToList();
你应该可以做这样的事情:
List<MyType2> list2 = new List<MyType2>(list1.Select(x => new MyType2(x)));
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!!!
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.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.