Does LINQ “Query Syntax” Support Duck Typing?

后端 未结 2 1754
情书的邮戳
情书的邮戳 2021-01-17 05:08

Regarding LINQ query syntax...

var foo = new List { 1, 2 };

var boo = from n in foo
            where n > 1
            select n;
2条回答
  •  感动是毒
    2021-01-17 05:25

    What you're missing is that List implements IEnumerable. Thus, "I always thought this syntax was limited to operating on IEnumerable" is technically true, though in a limited fashion. IQueryable implements IEnumerable as well, along with IList and arrays. Thus, you can perform linq queries against anything that implements IEnumerable.

    Since Joker<> doesn't implement IEnumerable<>, your query attempt will fail. The Select<>(), Where<>(), etc. extension methods are built around IEnumerable<>. So, if you want to select from oof, you just need to update your definition of Joker<>

    public class Joker : IEnumerable
    {
      // (actually implement IEnumerable functionality
    }
    

    (Edit: Answer did make some sense in the context of the originally-formatted question. Edited question makes my response obsolete)

提交回复
热议问题