In some of the work I do I have to combine several lists into one list and only add a item if it is unique by some arbitrary rule. I have done this so often in the last month I was about to write a code snipit for it. Then I started learning about template functions and realized I could just make one function to do this for me. I started out using Contains(vale,IEqualityComparer<>) to see if the item was already in a list this was a lot of effort and I never did figure out how to make a IEqualityCompare delegate. But there is this nice little method on lists called Exists which takes a predicate for comparisone. Which solved all my problems. The extention function I came up with seen below is probaly my favrite so far.
36 public static void AddIfUnique<T>(this List<T> tList, T toInsert, Func<T,T,bool> func)
38 if (!tList.Exists(p => func(p,toInsert)))
The usage for it is as follows.
15 DirectoryInfo mainDir = new DirectoryInfo(@"c:\");
16 List<FileSystemInfo> item = new List<FileSystemInfo>();
18 DirectoryInfo mainDir2 = new DirectoryInfo(@"e:\");
19 List<FileSystemInfo> tList = new List<FileSystemInfo>();
21 tList.ForEach(c => item.AddIfUnique(c, (k, j) => k.Name == j.Name));
In the above code the item list will end up with all file names that are unique. While this example is not the most useful example out there it does show how it works.