Hi I need to sort a list then take the first 6 in .net 2.0
for example the code below sorts but does not take the first 6 how can i do this?
allFeeds.Sort(delegate(SimplifiedFeedItem p1, SimplifiedFeedItem p2)
{ return -p1.PublishDate.CompareTo(p2.PublishDate); });
allFeeds.ForEach(delegate(SimplifiedFeedItem p)
{
// do for the first 6 items only
}
);
In .NET 3.5 the canonical answer would be to use
Take. Fortunately, you can write this very easily for .NET 2.0:Then you can do:
Alternatively, you could just get hold of LINQBridge and have the whole of LINQ to Objects available to you…
The advantage of doing things this way is that when you eventually upgrade to .NET 3.5 or later, you’ll have a solution which can be turned into idiomatic LINQ very easily:
Note that error checking with iterator blocks is slightly tricky – you need to write a “normal” method which does the argument checking, and then call the iterator separately; otherwise the exception isn’t throw until you start iterating.