Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend the options of LINQ

Tags:

c#

.net

linq

I would like to be able to write the following in a LINQ query:

from item in list
collate by item.Property
select item;

to use this code, I have the following method:

public static IEnumerable<T> CollateBy<T,TKey>(
                                 this IEnumerable<T> arr, 
                                 Func<T, TKey> keySelector)
{
    foreach (var group in arr.GroupBy(keySelector))
    {
        foreach (var item in group)
            yield return item;
    }
}

How do I write this method so that the query stated above would work?

like image 371
Eli Falk Avatar asked Jul 08 '18 14:07

Eli Falk


People also ask

What are LINQ extension methods?

Linq provides standard query operators like filtering, sorting, grouping, aggregation, and concatenations, and it has many operators to achive many types of functionalities, which are called extension methods, in LINQ.

What is the difference between query syntax and method syntax in LINQ?

Query syntax and method syntax are semantically identical, but many people find query syntax simpler and easier to read. Some queries must be expressed as method calls. For example, you must use a method call to express a query that retrieves the number of elements that match a specified condition.


1 Answers

You can't do this. from, in, by and select are C# keywords. So that you ask is equivalent to define a custom keyword, which is not possible.

For the record, each LINQ query written in query syntax (like the one you have mentioned) under the hood is compiled in method calls that have the same result.

For instance the following query:

var adultCustomers = from customer in customers
                     where customer.Age > 18;

is equivalent to the query below:

var adultCustomers = customers.Where(customer=>customer.Age>18);

Under the hood the compiler initially translates the first query to the second one. The first version is just syntactic sugar.

In your case the following query (method syntax) is might that you want:

var result = list.CollateBy(item => item.Property);
like image 163
Christos Avatar answered Sep 23 '22 20:09

Christos