Generic List - Split list

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?
 
B

Bruce Wood

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top