How do I change my new list without changing the original list?

后端 未结 11 1896
萌比男神i
萌比男神i 2020-12-03 08:30

I have a list that gets filled in with some data from an operation and I am storing it in the memory cache. Now I want another list which contains some sub data from the li

11条回答
  •  忘掉有多难
    2020-12-03 09:13

    Even if you create a new list, the references to the items in the new list will still point to the items in the old list, so I like to use this extension method if I need a new list with new references...

    public static IEnumerable Clone(this IEnumerable target) where T : ICloneable
    {
        If (target.IsNull())
            throw new ArgumentException();
    
        List retVal = new List();
    
        foreach (T currentItem in target)
            retVal.Add((T)(currentItem.Clone()));
    
        return retVal.AsEnumerable();
    }
    

提交回复
热议问题