Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend the Query-Keywords in C# / LINQ?

Tags:

c#

select

linq

is it possible to extend the query-keywords of Linq (like: select, where, etc.) with own definitions?

Codeexample to make it clearer:

System.Collections.Generic.List<string> aList = 
    new System.Collections.Generic.List<string> { "aa", "ab", "ba", "bb" };

// instead of
string firstString = (from item in aList
                      where item.StartsWith("a")
                      select item).First();

// would be nice
string firstString = from item in aList
                     where item.StartsWith("a")
                     selectFirst item;

// or something else
from item in aList
where item.StartsWith("a")
WriteLineToConsole item;

I think it's not possible, but still hoping ;)

like image 234
germanSharper Avatar asked Aug 31 '11 09:08

germanSharper


People also ask

What is the function of the from query keyword?

A query expression must begin with a from clause. It specifies a data source together with a range variable. The range variable represents each successive element in the source sequence as the source sequence is being traversed.

Can LINQ select return null?

in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Save this answer. Show activity on this post.

What is LINQ syntax?

LINQ query syntax is consist of a set of query keywords defined into the . NET Framework version 3.5 or Higher. This allows the programmer or developers to write the commands similar to SQL style in the code(C# or VB.NET) without using quotes. It is also know as the Query Expression Syntax.

What are LINQ query expressions?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


1 Answers

You can't add your own contextual keywords, but you can affect what the existing ones mean.

For example, this code:

string firstString = (from item in aList
                      where item.StartsWith("a")
                      select item).First();

is effectively preprocessed to:

string firstString = aList.Where(item => item.StartsWith("a"))
                          .First();

... so if you change what those Where and First method calls mean, you can affect the behaviour.

If you've got the stomach for it, you might want to look at this Stack Overflow answer I wrote a while ago which changes the behaviour of where in LINQ to Entities in certain circumstances. It's evil, evil code though.

like image 59
Jon Skeet Avatar answered Sep 23 '22 15:09

Jon Skeet