我如何在c#中不使用foreach将一个列表中包含的项目转移到另一个列表中?
当前回答
此方法将创建列表的副本,但您的类型应该是可序列化的。
使用:
List<Student> lstStudent = db.Students.Where(s => s.DOB < DateTime.Now).ToList().CopyList();
方法:
public static List<T> CopyList<T>(this List<T> lst)
{
List<T> lstCopy = new List<T>();
foreach (var item in lst)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, item);
stream.Position = 0;
lstCopy.Add((T)formatter.Deserialize(stream));
}
}
return lstCopy;
}
其他回答
这是如果需要将一个属性复制到另一个列表:
targetList.AddRange(sourceList.Select(i => i.NeededProperty));
你可以试试这个:
List<Int32> copy = new List<Int32>(original);
或者如果你使用c# 3和。net 3.5,使用Linq,你可以这样做:
List<Int32> copy = original.ToList();
我看到这个答案仍然得到了点赞。好吧,这里有一个秘密给你:上面的答案仍然是使用一个foreach。请不要再投票了。
好的,这工作得很好 根据上面的建议,GetRange()不适合我使用列表作为参数…所以从上面的帖子中让事情变得甜蜜一点:(谢谢大家:)
/* Where __strBuf is a string list used as a dumping ground for data */
public List < string > pullStrLst( )
{
List < string > lst;
lst = __strBuf.GetRange( 0, __strBuf.Count );
__strBuf.Clear( );
return( lst );
}
要将一个列表的内容添加到已经存在的另一个列表,您可以使用:
targetList.AddRange(sourceList);
如果您只是想创建一个列表的新副本,请参阅顶部的答案。
public static List<string> GetClone(this List<string> source)
{
return source.Select(item => (string)item.Clone()).ToList();
}