How do I transfer the items contained in one List
to another in C# without using foreach
?
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;
}