Clone
Allows you to clone an etire generic list of cloneable items.
Source
public static IList<T> Clone<T>(this IList<T> listToClone) where T:ICloneable {
return listToClone.Select(item => (T)item.Clone()).ToList();
}
Example
public class Item :ICloneable {
public int ID { get; set; }
public string ItemName { get; set; }
public object Clone() {
return MemberwiseClone();
}
}
static class CloneTest {
public static IList<T> Clone<T>(this IList<T> listToClone) where T:ICloneable {
return listToClone.Select(item => (T)item.Clone()).ToList();
}
public static void RunTest(){
//Populate our initial list
var items = new List<Item> {new Item {ID = 1, ItemName = "Item1"},
new Item {ID = 2, ItemName = "Item2"},
new Item {ID = 3, ItemName = "Item3"},
new Item {ID = 4, ItemName = "Item4"}};
//Create a Clone
var itemsClone = items.Clone();
//Baseline test, expect Match comparing 2nd item in list
Console.WriteLine(items[2] == items[2] ? "Match" : "Different");
//Clone test, expect Different comparing 2nd item of each
Console.WriteLine(items[2] == itemsClone[2] ? "Match" : "Different");
}
}
static void Main() {
CloneTest.RunTest();
Console.ReadLine();
return;
}
RESULTS:
Match
Different
Author: Jeff Reddy
Submitted on: 19 aug. 2011
Language: C#
Type: System.Collections.Generic.IList<T>
Views: 6947