通过收集在C#中的一个子集枚举?
-
23-08-2019 - |
题
有没有通过只在C#集合的子集枚举的好办法?也就是说,我有大量的对象(比如,1000)的集合,但我想只通过单元250枚举 - 340是否有一个很好的方式来获得集合的子集的枚举,不使用另一类别?
编辑:应该提到,这是使用的.NET Framework 2.0
解决方案
尝试使用以下
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);
其他提示
我想保持它的简单(如果你并不一定需要枚举):
for (int i = 249; i < Math.Min(340, list.Count); i++)
{
// do something with list[i]
}
适应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
}
再次适应Jarad的代码,这extention方法将让你由中定义的一个子集项目的,而不是指数。
//! Get subset of collection between \a start and \a end, inclusive
//! Usage
//! \code
//! using ExtensionMethods;
//! ...
//! var subset = MyList.GetRange(firstItem, secondItem);
//! \endcode
class ExtensionMethods
{
public static IEnumerable<T> GetRange<T>(this IEnumerable<T> source, T start, T end)
{
#if DEBUG
if (source.ToList().IndexOf(start) > source.ToList().IndexOf(end))
throw new ArgumentException("Start must be earlier in the enumerable than end, or both must be the same");
#endif
yield return start;
if (start.Equals(end))
yield break; //start == end, so we are finished here
using (var e = source.GetEnumerator())
{
while (e.MoveNext() && !e.Current.Equals(start)); //skip until start
while (!e.Current.Equals(end) && e.MoveNext()) //return items between start and end
yield return e.Current;
}
}
}
您也许能够做一些使用LINQ。我会做的方式是将对象转换成数组,然后我可以选择我想基于阵列的ID来处理的项目。
如果你发现你需要做切片和列表和集合的切割相当数量的,它可能是值得攀登学习曲线进入的所述C5通用收集库。
不隶属于 StackOverflow