Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphabetic GroupBy in Linq with a twist

Tags:

c#

linq

I have a tricky question. I'm looking for the most concise, hackiest way of achieving the following:

query = (from book in library.books.OrderBy(x=>x.title)
         group book by
         new { title = book.title[0].ToString(), yadiyada="" });

The result of which is all of the books in the library grouped by the first letter. Yadiyada is because my group object is not a simple string but an object.

I'm wondering if there's a pure LINQ way of making it so that the grouping is 'A', 'B', 'C', ... 'Z', but all others fall into a single grouping called '123!@#'.

In other words, I want only one grouping for all non alpha characters (A->Z + Rest).

I can do this in many ways if I get verbose (currently I'm simply making a union of two Linq statements), but that's not the purpose of this question. I'm wondering if someone can come up with a really neat way of doing it...

like image 721
MB. Avatar asked Feb 03 '16 13:02

MB.


1 Answers

It depends on what a pure LINQ way means. If you want to group it with a single query, you can try something like this:

query = (from book in library.books.OrderBy(x=>x.title)
         let c = book.title[0]
         group book by
         new { title = char.IsLetter(c) ? c.ToString() : "123!@#", yadiyada="" });
like image 109
Eldar Dordzhiev Avatar answered Sep 18 '22 18:09

Eldar Dordzhiev