我如何在c#中不使用foreach将一个列表中包含的项目转移到另一个列表中?


当前回答

public static List<string> GetClone(this List<string> source)
{
    return source.Select(item => (string)item.Clone()).ToList();
}

其他回答

用于元素列表

List<string> lstTest = new List<string>();

lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");

如果你想复制所有元素

List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);

如果你想复制前3个元素

List<string> lstNew = lstTest.GetRange(0, 3);

这里有另一种方法,但它比其他方法差一点。

List<int> i=original.Take(original.count).ToList();
public static List<string> GetClone(this List<string> source)
{
    return source.Select(item => (string)item.Clone()).ToList();
}

要将一个列表的内容添加到已经存在的另一个列表,您可以使用:

targetList.AddRange(sourceList);

如果您只是想创建一个列表的新副本,请参阅顶部的答案。

此方法将创建列表的副本,但您的类型应该是可序列化的。

使用:

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