How do I copy items from list to list without foreach?

后端 未结 8 1633
野的像风
野的像风 2020-11-30 17:42

How do I transfer the items contained in one List to another in C# without using foreach?

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 18:12

    This method will create a copy of your list but your type should be serializable.

    Use:

    List lstStudent = db.Students.Where(s => s.DOB < DateTime.Now).ToList().CopyList(); 
    

    Method:

    public static List CopyList(this List lst)
        {
            List lstCopy = new List();
            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;
        }
    

提交回复
热议问题