Generic List - Split list

Generic List - Split list

Post by maxtoro » Sun, 05 Nov 2006 03:08:26


I know how to work the .FindAll method of the List class, but is there
a way to split a list into 2 lists, one containing all the items that
match a certain criteria and one that doesn't?
 
 
 

Generic List - Split list

Post by Bruce Woo » Sun, 05 Nov 2006 03:54:47


No, but it would be pretty simple to write one. Off the top of my head:

public static void SplitList<T>(List<T> list, Predicate<T> match, out
List<T> matchedList, out List<T> didNotMatchList)
{
matchedList = new List<T>();
didNotMatchList = new List<T>();
foreach (T item in list)
{
if (match(item))
{
matchedList.Add(item);
}
else
{
didNotMatchList.Add(item);
}
}
}

If you're using C# 3.0 (I think it is) you can also do that funky
extension method thing to add the method directly to List<T> (although
I'm not 100% sure that they work with generics):

public static class Extensions
{
public static void Split<T>(this List<T> list, Predicate<T> match,
out List<T> matchedList, out List<T> didNotMatchList)
{
matchedList = new List<T>();
didNotMatchList = new List<T>();
foreach (T item in list)
{
if (match(item))
{
matchedList.Add(item);
}
else
{
didNotMatchList.Add(item);
}
}
}
}

Then you could invoke it like this:

myList.Split(matchPredicate, out matchedList, out didNotMatchList);