Is it possible to use Linq and lambdas without including a System.Linq namespace?

后端 未结 3 569
一整个雨季
一整个雨季 2020-12-11 04:57

Some time ago, I\'ve been working on a quite twisted project - I could only write the code in the single scope and it would be later put in a C# function (by another module)

相关标签:
3条回答
  • 2020-12-11 05:00

    Without the using directive, methods like .Where, .Select, will not resolve. That means that LINQ the language part will not work. You would have to code it long-hand (and backwards!):

    List<int> _NewList = System.Linq.Enumerable.ToList(
        System.Linq.Enumerable.Where(_Numbers, _Number => _Number % 2 == 0)
    );
    

    Note that this becomes increasing complex for longer examples with groups, orders, "let"s, joins etc. Unless you are doing something fairly simple, it would be advisable to just find a way to add the using directive.

    Note, however, that if _Numbers is a List<T>, you can just use (for this single example):

    List<int> _NewList = _Numbers.FindAll(_Number => _Number % 2 == 0);
    
    0 讨论(0)
  • 2020-12-11 05:17

    Not very clear why you can not access file "header", but if the issue that you can not type in the begining of the file using dirrective, you can still use full qualified name of the type, like:

    System.Linq.Enumerable(...)
    

    To make this work, you naturally, need to include also correct references.

    If this is not what you're asking for, please clarify.

    0 讨论(0)
  • 2020-12-11 05:23

    You can write such code:

    System.Linq.Enumerable.Where(_NewList, n => n % 2 == 0)
    

    But, be careful: if your class implements interface IQueryable<T>, code above will do the work, but more slower.

    System.Linq.Queryable.Where(_NewList, n => n % 2 == 0)
    

    Because IQueryable is the way to produce C# in other DSL language, like SQL. With other where conditions your SQL server can choose needed elements as fast as it can. But if you working with IEnumerable or System.Linq.Enumerable there no be optimise on server-side, you'll got a full list of items, they all will be loaded to the memory and filtered in memory.

    0 讨论(0)
提交回复
热议问题