English 中文(简体)
将物体清单按一行制成另一类清单
原标题:Copy a list of objects to another typed list in one line of code

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.

我现在这样做:

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);
}

是否有办法实现这一一线(如果认为与林克有可能的话)?

最佳回答
var type2objects = type1objects.Select(o => new MyType2(o)).ToList();
问题回答

您可以使用与Linq的Select()进行简单的预测,然后用ToList(在这份清单中填写一个名单:

var type2objects = type1objects.Select( x => new MyType2(x))
                               .ToList();
var type2objects = type1objects.Select(type1obj => new MyType2(type1obj)).ToList();

如果你只复制清单1至清单2的所有内容,则将获得这些内容的真实复制件。 你们只有另一个包含同样内容的清单!

你们还可能从科伊拉带走几英里。 变化类型取决于您重新转换:

List<MyType2> type2objects = type1objects.Select(
    type1object => Convert.ChangeType(type1object, typeof(MyType2))
    ).ToList();
List<MyType2> type2objects = new List<MyType2>();
type2objects.AddRange(type1objects.Select(p => new MyType2(p)));

这样,你甚至可以保存<代码>类型2目标/代码>中所载的数值。

我补充说,你知道<代码> 类型1物体/代码”的大小,因此你可以加快:

List<MyType2> type2objects = new List<MyType2>(type1objects.Count);

在此,预先设定了<代码>类型2目标>的能力。

或者,如果你重新使用“旧2”<代码>,2objects

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.

有些人将称这种过早优化,现在就是这样。 但could需要。

你们应该能够做这样的事情:

List<MyType2> list2 = new List<MyType2>(list1.Select(x => new MyType2(x)));




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签