Friday, September 19, 2008

Adding unique items to a list the fun way

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)
37 {
38    if (!tList.Exists(p => func(p,toInsert)))
39    {
40        tList.Add(toInsert);
41    }
42 }

The usage for it is as follows.

15 DirectoryInfo mainDir = new DirectoryInfo(@"c:\");
16 List<FileSystemInfo> item = new List<FileSystemInfo>();
17 item.AddRange(mainDir.GetFiles());
18 DirectoryInfo mainDir2 = new DirectoryInfo(@"e:\");
19 List<FileSystemInfo> tList = new List<FileSystemInfo>();
20 tList.AddRange(mainDir2.GetFiles());
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.

1 comment:

James and Crystal said...

Good post, I'm surprised there isn't anything in the .Net framework for a unique list and if there is I'm missing it. I think you might be able to pull a similar type of execution but using the Distinct extension method but I'd have to try it out first.