[英]Linq and cloning Objects in C#
This question is not about cloning objects but about the correct use of Linq to use an extension method to clone a list of objects.Code if just for illustration. 这个问题不是关于克隆对象的问题,而是关于如何正确使用Linq来使用扩展方法来克隆对象列表的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<MyObj> myObjs = DB.GetAllMyObjs(); //fictitious database calls returns a list of Objs
//I now want to use my extension method clone to clone all the MyObjs in myObjs
// this throws an error;
List<MyObj> myObj2 = myObjs.ForEach(a => a.Clone()).ToList(); //ERROR = "."cannot be applied to type void
}
}
public class MyObj
{
public int Id { get; set; }
}
public static class MyObjExtentions
{
public static MyObj Clone(this MyObj myObj)
{
var myObjClone = new MyObj();
myObjClone.Id = myObj.Id;
return myObjClone;
}
}
} }
I am getting an error on the Linq code. 我在Linq代码上遇到错误。 is it possible to do this or do you need a foreach loop.
是否有可能做到这一点,或者您需要一个foreach循环。
Change ForEach
To Select
更改
ForEach
Select
List<MyObj> myObj2 = myObjs.Select(a => a.Clone()).ToList();
ForEach is part of the list implementation. ForEach是列表实现的一部分。 not linq
不是linq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.