Re: Generic List - Split list

Tech-Archive recommends: Speed Up your PC by fixing your registry




maxtoroq wrote:
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);

.



Relevant Pages

  • Re: foreach enhancement
    ... >> I also don't think there is any value in using foreach here. ... >> One of the current rules in my lists spec is that IEnumerable objects are ... >> an IEnumerable value, which allows ranges to be used as ... >> strings, I wouldn't have a problem introducing override syntax. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: foreach enhancement
    ... > syntax sufficently that its valid outside of foreach and isin clauses. ... bool userflag; ... This is why I consider the solution to be non-dynamic, as each foreach loop ... independently of Lists at all? ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: foreach enhancement
    ... [yield GetStringForfor 1...1000]. ... I also don't think there is any value in using foreach here. ... although strings can be included in, and added to, lists, I ... > wouldn't allow strings to be used to declare ranges. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Weird Error Msg
    ... foreach file $txtfile { ... want to match a glob-style pattern, a regular expression, or a fixed string. ... lists, and the foreach expects it's second argument to be a list. ... wrote proper Tcl lists, one per line). ...
    (comp.lang.tcl)
  • Re: How can I list down all builtin functions?(Re: Read a text file starting from the bottom)
    ... what to "perldoc -f"? ... This doesn't list "all builtin functions", it lists all environment variables ... foreach $fieldname{ ... You have three tests in that loop. ...
    (perl.beginners)