Linq按照条件

时间:2018-02-07 13:28:20

标签: c# linq

这就是我的EF模型响应表的样子

Question_ID         Responce

1                   Agree
1                   Agree
1                   Tend to Agree
1                   Tend to Agree

2                   Agree
2                   Agree
2                   Tend to Agree
2                   Tend to DisAgree

3                   DisAgree
3                   DisAgree
3                   Tend to DisAgree
3                   Tend to DisAgree

在上面的例子中。我想根据同意(同意应包括在计算时同意倾向)和DisAgree按问题ID排序。在计算时,DisAgree应该包括Tend to Disagree)

因此,同意订单应如下

1 // (Got 4 Agree)
2 // (Got 3 Agree)
3 // (Got 0 Agree)

Disgaree应如下所示

3 // (Got 4 Disagree)
2 // (Got 1 Disagree)
1 // (Got 0 Disagree)

Simle Linq根据总响应次数进行排序。 我期待基于上述要求修改linq

db.Questions.OrderBy(x => x.Responces.Count).Select(y=>new { y.Question_ID,count= y.Responces.Count()}).ToList();

2 个答案:

答案 0 :(得分:1)

你不能同时用两把钥匙组。一个组需要一个唯一密钥。

然而,您可以做到以下几点:

db.Questions.GroupBy(x=>((x.Responce == "Agree")|(x.Responce == "Tend
to Agree")));

这会为您提供两个键TRUEFALSE。在TRUE组中,所有值均为"Agree""Tend to Agree"FALSE组中将包含所有其他组。

答案 1 :(得分:0)

我建议您将响应列转换为类似这样的枚举类型:

[Flags]
public enum Response
{
    Agree = 1,
    Unknown = 2,
    Disagree = 4,
    TendToAgree = Agree | Unknown,
    TendToDisagree = Unknown | Disagree
}

通过这种方式,您可以检查所需的标记并计算条目:

var agreed = list.Where(x => x.QuestionID == 1).Count(x => x.Response.HasFlag(Response.Agree));
var disagreed = list.Where(x => x.QuestionID == 1).Count(x => x.Response.HasFlag(Response.Disagree));