Search code examples
c#linqdatatablelinq-to-dataset

LINQ query with SELECT and two GROUP-BY condition


What's the equivalent LINQ instruction for a Datatable of the following SQL query:

SELECT code_direction, count(TP) AS CN 
FROM table1 
WHERE cod_time = 'A011' 
GROUP BY TP,code_direction;

and how to get the result into a new datatable?

I tried to convert it but I there're some errors. Someone could take a look on this:

    var query = from t in table1.AsEnumerable()
                group t by new { t.TP, t.code_direction }
                    into grp
                    select new
                    {
                        grp.Key.code_direction,
                        CN = grp.Count(t.TP)
                    };
    foreach (var x in query)
    {
        Console.Write(x.code_direction);
        Console.Write(x.CN);
    }

Solution

  • As far as your first question goes. The LINQ equivalent of the SQL query is:

    var query = from t in table1.AsEnumerable()
                where t.cod_time == "A011"
                group t by new { t.TP, t.code_direction }
                    into grp
                    select new
                    {
                        grp.Key.code_direction,
                        CN = grp.Count()
                    };
    

    Note that you don't have to pass any argument to grp.Count(). (For the obvious reason that in SQL COUNT(TP) is the same as COUNT(*), i.e. just count the number of rows. The story would be different if you'd use COUNT(DISTINCT TP) or similar.)

    As far as the second question goes, if your query just returned an IEnumerable<T> where T is DataRow (i.e. a query like table1.AsEnumerable().Where(r => r.cod_time == "A011")) then you could just the DataTableExtensions.CopyToDataTable extension method. As your query returns an anonymous type however, you will have to follow these instructions found on MSDN.