Get the first characters of a column in a table using linq

I am looking for the LINQ equivalent for the following query:

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

Thanks in advance.

+3
source share
1 answer

Well, I don’t know if it can translate into the corresponding SQL query, but you can try the following:

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 what you expect to see?

+7
source

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


All Articles