How to convert this request to LINQ?

时间:2017-08-05 12:17:59

标签: mysql linq

  • SELECT StepID, count() as nb FROM Question GROUP BY StepID ORDER by nb;

2 个答案:

答案 0 :(得分:0)

您应该了解LINQ的基础知识。 Microsoft Docs有一整节专门介绍LINQ:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/

如果您的数据位于List<Question>类型的var ret = from q in questions group q by q.StepId into grouped let count = grouped.Count() orderby count select new { StepId = grouped.Key, nb = count }; 列表中,那么您应该可以像这样转换您的查询:

{{1}}

答案 1 :(得分:0)

查询理解语法:

from q in questions
group q by q.StepId into g
select new { StepId = g.Key, Count = g.Count() } into stepCount
orderby stepCount.Count
select stepCount;

方法语法完全相同(我更喜欢,因为它可以使所有查询语法加上更多,而且通常更紧凑):

questions
.GroupBy(q => q.StepId)
.Select(g => new { StepId = g.Key, Count = g.Count() })
.OrderBy(stepCount => stepCount.Count)

使用另一个GroupBy重载的变体:

questions
.GroupBy(q => q.StepId, (key, values) => new { StepId = key, Count = values.Count() })
.OrderBy(stepCount => stepCount.Count);