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

后端 未结 8 1634
野的像风
野的像风 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:01

    OK this is working well From the suggestions above GetRange( ) does not work for me with a list as an argument...so sweetening things up a bit from posts above: ( thanks everyone :)

    /*  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 );
    }
    
    0 讨论(0)
  • 2020-11-30 18:01

    Here another method but it is little worse compare to other.

    List<int> i=original.Take(original.count).ToList();
    
    0 讨论(0)
  • 2020-11-30 18:02

    And this is if copying a single property to another list is needed:

    targetList.AddRange(sourceList.Select(i => i.NeededProperty));
    
    0 讨论(0)
  • 2020-11-30 18:04

    To add the contents of one list to another list which already exists, you can use:

    targetList.AddRange(sourceList);
    

    If you're just wanting to create a new copy of the list, see Lasse's answer.

    0 讨论(0)
  • 2020-11-30 18:11

    You could try this:

    List<Int32> copy = new List<Int32>(original);
    

    or if you're using C# 3 and .NET 3.5, with Linq, you can do this:

    List<Int32> copy = original.ToList();
    
    0 讨论(0)
  • 2020-11-30 18:12

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

    Use:

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

    Method:

    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;
        }
    
    0 讨论(0)
提交回复
热议问题