First 6 from a foreach .net 2.0
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:
public static IEnumerable<T> Take<T>(IEnumerable<T> source, int limit)
{
// Error checking omitted
using (IEnumerator<T> iterator = source.GetEnumerator())
{
for (int i = 0; i < limit; i++)
{
if (!iterator.MoveNext())
{
yield break;
}
yield return iterator.Current;
}
}
}
Then you can do:
foreach (SimplifiedFeedItem item in Take(allFeeds, 6))
{
// Do stuff
}
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:
foreach (SimplifiedFeedItem item in allFeeds.Take(6))
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.
Why don't you use a simple for loop in such a case ?
allFeeds.Sort (...);
for( int i = 0; i < 6; i++ )
{
DoSomething (allFeeds[i]);
}
or
allFeeds.Sort (...);
for( int i = 0; i < allFeeds.Count; i++ )
{
if( i == 6 ) break;
DoSomething(allFeeds[i]);
}
The latter is the better option, since the first option will throw an exception when your collection contains less then 6 elements.
Either way, I think that using a for-loop is much more readable in this case.
精彩评论