Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Query in LINQ equivalent to sql query

Tags:

c#

sql

linq

I have a dataset that contains caller, callee fiels and i need some LINQ query to operate on this dataset equivalent to this sql query

SELECT CASE
     WHEN caller < callee THEN callee
     ELSE caller
   END      AS caller1,
   CASE
     WHEN caller < callee THEN caller
     ELSE callee
   END      AS caller2,
   Count(*) AS [Count]
    FROM   YourTable
   GROUP  BY CASE
        WHEN caller < callee THEN callee
        ELSE caller
      END,
      CASE
        WHEN caller < callee THEN caller
        ELSE callee
      END 
like image 779
Rajeev Kumar Avatar asked Oct 07 '22 08:10

Rajeev Kumar


2 Answers

Is this what you are after?

DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable("dataTable");

dataTable.Columns.Add("caller", typeof(String));
dataTable.Columns.Add("callee", typeof(String));

dataTable.Rows.Add("999", "888");
dataTable.Rows.Add("888", "999");
dataTable.Rows.Add("999", "555");
dataTable.Rows.Add("555", "333");
dataTable.Rows.Add("555", "999");

dataSet.Tables.Add(dataTable);

string filter = "999";

var result = dataSet.Tables["dataTable"].Select().Select(dr =>
    new
    {
        caller1 = StringComparer.CurrentCultureIgnoreCase.Compare(dr["caller"], dr["callee"]) < 0 ? dr["callee"] : dr["caller"],
        caller2 = StringComparer.CurrentCultureIgnoreCase.Compare(dr["caller"], dr["callee"]) < 0 ? dr["caller"] : dr["callee"]
    })
        .Where(dr => String.IsNullOrEmpty(filter) || dr.caller1 == filter || dr.caller2 == filter)
        .GroupBy(drg => new { drg.caller1, drg.caller2 } )
        .Select(drg => new { drg.Key.caller1, drg.Key.caller2, count = drg.Count() });
like image 99
Seb Boulet Avatar answered Oct 17 '22 21:10

Seb Boulet


This is what you're looking for, note the use of range variables which helps us reuse the case statement and simplify the LINQ query.

var query = from y in YourTable
            //place the result of the case statement into a range variable so we can reuse it for the grouping
            let caller1 = y.caller < y.callee ? y.callee : y.caller
            let caller2 = y.caller < y.callee ? y.caller : y.callee
            //group the results
            group y by new { caller1, caller2 } into grouping
            select new
            {            
                //get the range variables from the grouping key
                grouping.Key.caller1,
                grouping.Key.caller2,
                //get the count of the grouping
                Count = grouping.Count(),
            };
like image 36
Doctor Jones Avatar answered Oct 17 '22 19:10

Doctor Jones