.net - 与 LINQ 一起使用的集合类的要求

标签 .net linq sharepoint ienumerable

我一直认为类应该满足能够使用 Where() 的足够要求是实现 IEnumerable

但是今天我的一个 friend 问我一个问题,为什么他不能将Where() 应用于SPUserCollection 的对象?类(它来自 Sharepoint)。由于此类派生自 SPBaseCollection它实现了 IEnumerable - 我希望一切都应该没问题。但事实并非如此。

有什么想法,为什么?

最佳答案

LINQ 扩展方法在 IEnumerable<T> 上定义, 不是 IEnumerable .例如,请参阅 Where<T> 签名:

public static IEnumerable<TSource> Where<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate
)

为了缓解这个问题,LINQ Cast<T> 扩展方法变成一个 IEnumerable进入 IEnumerable<T>然后可以与普通的 LINQ 函数一起使用。

在下面的例子中,你不能做 e.Where(...) , 但你可以 Cast然后使用 Where .

int[] xs = new[] { 1, 2, 3, 4 };
IEnumerable e = xs;
var odds = e.Cast<int>().Where(x => x % 2 == 1);

不幸的是,在处理 .NET BCL 中的前泛型 API 时需要大量使用它。

关于.net - 与 LINQ 一起使用的集合类的要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3878778/

相关文章:

尽管所有操作都已完成,但 Sharepoint 工作流仍为 "in progress"

.net - ELSA-Workflows 能走多远?

c# - .docx文件生成

c# - Linq Complex OrderBy by Props 属性

c# - 从列表中获取数据以在代码中使用?

c# - 在通过 Sharepoint 中的代码创建发布页面之前,如何检查发布页面是否存在?

c# - 如何正确捕获调用存储过程的返回值

c# - .NET Framework 4.5 及更高版本是否可用于 Embedded Compact 2013 和 Windows 10 IoT Core?

c# - 无效操作异常 : An exception was thrown while attempting to evaluate a LINQ query parameter expression

SharePoint 2010 你如何算出一个网站是什么类型的网站呢?