[英]Linq and cloning Objects in C#
这个问题不是关于克隆对象的问题,而是关于如何正确使用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;
}
}
}
我在Linq代码上遇到错误。 是否有可能做到这一点,或者您需要一个foreach循环。
更改ForEach
Select
List<MyObj> myObj2 = myObjs.Select(a => a.Clone()).ToList();
ForEach是列表实现的一部分。 不是linq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.