5

我有一个包含调用者、被调用者字段的数据集,我需要一些 LINQ 查询来操作这个数据集,相当于这个 sql 查询

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 
4

3 回答 3

3

这就是你所追求的吗?

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() });
于 2012-10-15T09:12:40.797 回答
1

这就是您要查找的内容,请注意范围变量的使用,这有助于我们重用 case 语句并简化 LINQ 查询。

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(),
            };
于 2012-10-15T09:53:53.600 回答
0
SELECT CASE
  WHEN caller < callee THEN callee
  ELSE caller
END      AS caller1

被翻译成

caller1 = x.caller < x.callee ? x.callee : x.caller
于 2012-10-15T08:47:39.247 回答