mvcstudent
mvcstudent

Reputation: 37

Grouping strings by first character (alpha and numeric)

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")?

Upvotes: 2

Views: 2097

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500873

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:

Products.GroupBy(p = {
    char c = p.Name[0];
    return c >= '0' && c <= '9' ? '0' : char.ToUpper(c);
});

(Note that ToUpper is 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 let clause to do the same sort of thing in a different way:

var query = from product in products
            let c = product.Name[0]
            group product by c >= '0' && c <= '9' ? '0' : char.ToUpper(c);

Upvotes: 7

Related Questions