[英]Case Query in LINQ equivalent to sql query
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我有一个包含调用者、被调用者字段的数据集,我需要一些 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
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() });
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.这就是您要查找的内容,请注意范围变量的使用,这有助于我们重用 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(),
};
SELECT CASE
WHEN caller < callee THEN callee
ELSE caller
END AS caller1
is translated into被翻译成
caller1 = x.caller < x.callee ? x.callee : x.caller
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.