Sunday, August 31, 2008

Collection Filter Function

Let's continue the topic of my previous blog on .Net Generic and Value Data Type with an example of collection filter function for generic value data types. This function takes two collections, the first one as input collection and another one as filter collection. The returned collection will filter out all the items in the filter collection from the first collection. In this case, in order to filter items, the value data type makes sense when comparing equalities for all the items in a collection to an item. For reference data types, however, it is hard to tell equality or not, by reference or property members? You even can expect multiple-levels if some property members are reference types.

public IEnumerable<T> FilerCollections<T>(
IEnumerable<T> list,
IEnumerable<T> filterList)
where T: struct
{
if ( list != null )
{
foreach (T item in list)
{
bool found = false;
if (filterList != null)
{
foreach (T filterItem in filterList)
{
if (filterItem.Equals(item))
{
found = true;
break;
}
}
}
if (!found)
{
yield return item;
}
}
}
}


Here is the test program:

Test t = new Test();
IEnumerable<int> list;
List<int> list1 = new List<int>(new int [] {1, 2, 3, 4});
List<int> list2 = new List<int>(new int[] {3});
list = t.FilerCollections<int>(list1, list2);
if (list != null)
{
foreach (int item in list)
{
Console.WriteLine("item: {0}", item);
}
}
else
{
Console.WriteLine("List is empty");
}


and the result screen:

0 comments: