有没有一种很好的方法来在C#中只枚举集合的一个子集?也就是说,我有一个包含大量对象(比如1000个)的集合,但我只想枚举250 - 340个元素。有没有一种好的方法来获得集合的子集的枚举数,而不使用另一个集合?
编辑:应该提到它使用的是.NET Framework2.0。
发布于 2009-05-19 20:01:37
请尝试以下操作
var col = GetTheCollection();
var subset = col.Skip(250).Take(90);或者更一般地说
public static IEnumerable<T> GetRange(this IEnumerable<T> source, int start, int end) {
// Error checking removed
return source.Skip(start).Take(end - start);
}编辑 2.0解决方案
public static IEnumerable<T> GetRange<T>(IEnumerable<T> source, int start, int end ) {
using ( var e = source.GetEnumerator() ){
var i = 0;
while ( i < start && e.MoveNext() ) { i++; }
while ( i < end && e.MoveNext() ) {
yield return e.Current;
i++;
}
}
}
IEnumerable<Foo> col = GetTheCollection();
IEnumerable<Foo> range = GetRange(col, 250, 340);发布于 2009-05-19 20:08:10
我喜欢保持简单(如果您不一定需要枚举器):
for (int i = 249; i < Math.Min(340, list.Count); i++)
{
// do something with list[i]
}发布于 2009-05-19 20:11:22
将Jared的原始代码改编为.Net 2.0:
IEnumerable<T> GetRange(IEnumerable<T> source, int start, int end)
{
int i = 0;
foreach (T item in source)
{
i++;
if (i>end) yield break;
if (i>start) yield return item;
}
}并使用它:
foreach (T item in GetRange(MyCollection, 250, 340))
{
// do something
}https://stackoverflow.com/questions/884732
复制相似问题