Reputation: 21160
I have a sorted generic list. I would like to return the first 10 that match a condition.
sort of like the method below but only the first 10 items
mySortedlist.FindAll(delegate(myclass tmp){ return tmp.ID == 123;});
Upvotes: 1
Views: 137
Reputation: 19609
Something like the following:
int count = 0;
mySortedlist.FindAll(delegate(myclass tmp){ return (tmp.ID == 123 && ++count <= 10);});
Upvotes: 8
Reputation: 1499770
Well, that will return a list already. You can create your own equivalent of Enumerable.Take
pretty easily:
public static IEnumerable<T> Take<T>(IEnumerable<T> source, int size)
{
int count = 0;
foreach (T item in source)
{
yield return item;
count++;
if (count == size)
{
yield break;
}
}
}
Then you can use:
List<myclass> filtered = mySortedlist.FindAll(delagate(myclass tmp) {
return tmp.ID == 123;
});
List<myclass> list = new List<myclass>(Helper.Take(filtered, 10));
Another option is to use LINQBridge so that you can use LINQ as much as possible - ideally using C# 3 even when you're targeting .NET 2.0, if possible. It'll make your life much simpler :)
Upvotes: 6