Alphabetic GroupBy in Linq with a swirl

I have a difficult question. I am looking for the most concise, hardest way to achieve the following:

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

As a result, all the books in the library are grouped by the first letter. Yadiyada is that my group object is not a simple string, but an object.

I am wondering if there is a clean LINQ way of doing this so that the grouping is 'A', 'B', 'C', ... 'Z', but all the rest fall into one group called “123! @ #”.

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

I can do this in many ways if I get verbose (currently I'm just doing a union of two Linq statements), but that is not the purpose of this question. I am wondering if anyone can come up with a really neat way to do this ...

+5
source share
2 answers

It depends on what pure LINQ method 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="" }); 
+8
source

I think you want some kind of conditional grouping. You can use the null character as a placeholder for all nonphase characters:

 HashSet<char> alpha = new HashSet<char>("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvqxyz"); var query = books .OrderBy(b => b.title) .Select(b => new{ Book = b, IsAlpha = alpha.Contains(b.title[0]), Char = b.title[0]} ) .Select(x => new{ x.IsAlpha, x.Book, Char = x.IsAlpha ? x.Char : '\0' } ) .GroupBy(x => x.Char); 
0
source

Source: https://habr.com/ru/post/1242204/


All Articles