替换 .NET 2.0 中的 Linq 方法
Replace Linq methods in .NET 2.0
我一直在到处寻找有关如何用标准 C# 代码替换 LINQ 中使用的某些方法的示例。我有一个非常简单的助手,我需要在 .NET 2.0 环境中使用它。我需要一个替代方案:
Skip()
Take()
using()
方法。我看过 this post,也看过 LINQBridge 解决方案,但想知道是否有任何资源可以解释如何用直接代码替代方法替换这些方法?
您可以自己编写 Take
和 Skip
public static IEnumerable<T> Skip<T>(IEnumerable<T> set, int count)
{
if(set == null) throw ArgumentNullException("set");
if(count < 0) throw ArgumentOutOfRangeException("count");
return SkipImp(set, count);
}
private static IEnumerable<T> SkipImp<T>(IEnumerable<T> set, int count)
{
foreach(var item in set)
{
if(count-- <= 0)
{
yield return item;
}
}
}
public static IEnumerable<T> Take<T>(IEnumerable<T> set, int count)
{
if(set == null) throw ArgumentNullException("set");
if(count < 0) throw ArgumentOutOfRangeException("count");
return TakeImp(set, count);
}
private static IEnumerable<T> TakeImp<T>(IEnumerable<T> set, int count)
{
foreach(var item in set)
{
if(count-- > 0)
{
yield return item;
}
else
{
yield break;
}
}
}
你必须做
var results = ContainingClass.Take(ContainingClass.Skip(list, 3), 4);
而不是
var results = list.Skip(3).Take(4);
请注意,在每种情况下使用两个单独方法的原因是在调用方法时抛出异常,而不是在迭代 IEnumerable<T>
时抛出异常。
我认为如果您使用支持扩展方法的编译器(VS 2008 及更高版本),您甚至可以使它们成为扩展方法,因为它是编译器版本而非 .net 版本的功能。
我一直在到处寻找有关如何用标准 C# 代码替换 LINQ 中使用的某些方法的示例。我有一个非常简单的助手,我需要在 .NET 2.0 环境中使用它。我需要一个替代方案:
Skip()
Take()
using()
方法。我看过 this post,也看过 LINQBridge 解决方案,但想知道是否有任何资源可以解释如何用直接代码替代方法替换这些方法?
您可以自己编写 Take
和 Skip
public static IEnumerable<T> Skip<T>(IEnumerable<T> set, int count)
{
if(set == null) throw ArgumentNullException("set");
if(count < 0) throw ArgumentOutOfRangeException("count");
return SkipImp(set, count);
}
private static IEnumerable<T> SkipImp<T>(IEnumerable<T> set, int count)
{
foreach(var item in set)
{
if(count-- <= 0)
{
yield return item;
}
}
}
public static IEnumerable<T> Take<T>(IEnumerable<T> set, int count)
{
if(set == null) throw ArgumentNullException("set");
if(count < 0) throw ArgumentOutOfRangeException("count");
return TakeImp(set, count);
}
private static IEnumerable<T> TakeImp<T>(IEnumerable<T> set, int count)
{
foreach(var item in set)
{
if(count-- > 0)
{
yield return item;
}
else
{
yield break;
}
}
}
你必须做
var results = ContainingClass.Take(ContainingClass.Skip(list, 3), 4);
而不是
var results = list.Skip(3).Take(4);
请注意,在每种情况下使用两个单独方法的原因是在调用方法时抛出异常,而不是在迭代 IEnumerable<T>
时抛出异常。
我认为如果您使用支持扩展方法的编译器(VS 2008 及更高版本),您甚至可以使它们成为扩展方法,因为它是编译器版本而非 .net 版本的功能。