I have a list of strings (product names) from which I need to create a product index (based on first-char of the product name) of the form “0-9”, “A”, “B”, … “Z”.
I am doing this:
Products.GroupBy(p => p.Name[0].ToUpper())
But that doesn’t work for the product names which start with “0”..”9″.
How do I modify the query to group all alphas into different groups (“A”..”Z”), as well as all numerics into a single group (“0-9”)?
You haven’t said whether you’re using LINQ to SQL or LINQ to Objects or something else. In LINQ to Objects I’d probably use:
(Note that
ToUpperis culture-sensitive, by the way – it’s not clear whether that’s what you want or not.)In LINQ to SQL (where block lambdas can’t be used, as they can’t be converted to expression trees) I’d probably use a
letclause to do the same sort of thing in a different way: