views:

57

answers:

1

I am looking for a LINQ equivalant for the following query:

SELECT UPPER(SUBSTRING(CompanyName, 1, 1)), COUNT(*) FROM MyTable GROUP BY UPPER(SUBSTRING(CompanyName, 1, 1))

Thanks in advance.

+3  A: 

Well, I don't know offhand whether or not it'll translate into the appropriate SQL query, but you could try this:

var query = from company in db.MyTable
            let firstChar = company.CompanyName.Substring(0, 1).ToUpper()
            group company by firstChar into grouped
            select new { FirstChar = grouped.Key, Count = grouped.Count() };

Here's a LINQ to Objects example:

using System;
using System.Collections.Generic;
using System.Linq;

class Test
{
    static void Main()
    {
        var companies = new[] {
            new { CompanyName = "One", CompanyID=1 },
            new { CompanyName = "Two", CompanyID=2 },
            new { CompanyName = "Three", CompanyID=3 },
            new { CompanyName = "Four", CompanyID=4 },
            new { CompanyName = "Five", CompanyID=5 },
            new { CompanyName = "Six", CompanyID=6 },
        };

        var query = from company in companies
            let firstChar = company.CompanyName.Substring(0, 1).ToUpper()
            group company by firstChar into grouped
            select new { FirstChar = grouped.Key, Count = grouped.Count() };

        foreach (var entry in query)
        {
            Console.WriteLine(entry);
        }
    }
}

Result:

{ FirstChar = O, Count = 1 }
{ FirstChar = T, Count = 2 }
{ FirstChar = F, Count = 2 }
{ FirstChar = S, Count = 1 }

Am I at least right in saying that's what you would expect to see?

Jon Skeet