Generic List - Split list

  • Thread starter Thread starter maxtoroq
  • Start date Start date
M

maxtoroq

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?
 
maxtoroq said:
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?

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);
 
Back
Top