简体   繁体   English

为什么我不能用 linq 迭代可以用 foreach 迭代的东西?

[英]Why can I not iterate over something with linq that can be iterated over with foreach?

I have a collection of table rows (type DataRowCollection ).我有一组表行(类型DataRowCollection )。 It is perfectly valid for me to write:我这样写是完全有效的:

foreach(var row in myDataRowCollection)
{
  // Something with row
}

Yet the following will not compile:然而,以下内容将无法编译:

myDataRowCollection.ToList();

or even甚至

myDataRowCollection.Select(...

What are these System.Linq extensions expecting that DataRowCollection doesn't implement?这些 System.Linq 扩展期望DataRowCollection不实现是什么?

foreach() is pattern based ( docs ), it does not actually rely on IEnumerable . foreach()是基于模式的( docs ),它实际上并不依赖于IEnumerable GetEnumerator() is enough. GetEnumerator()就足够了。

class A // note: no interface
{
    public IEnumerator GetEnumerator() { ...} 
}

Linq on the other hand is based on extension methods for IEnumerable<T> .另一方面,Linq 基于IEnumerable<T>的扩展方法。

Your DataRowCollection implements IEnumerable but not IEnumerable<DataRow> .您的DataRowCollection实现IEnumerable但不实现IEnumerable<DataRow> It is too old for Linq. Linq 太旧了。

But there are some helper methods available, myDataRowCollection.AsEnumerable().Select(...) should work.但是有一些辅助方法可用, myDataRowCollection.AsEnumerable().Select(...)应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM