[英]Nested Linq Group By
我有什么:清单
Class:规则 --> Class:术语 ---> 属性 Compare_Src 属性 Compare_Mode
我想要做什么:使用 Linq 语句来获取我的规则,按其 Compare_Src 和 Compare_Mode 的组合分组。
Static 一个组合的示例:(这里我得到了所有规则的列表,其中包含 Compare_src = EmpfaengerToken 和 Compare_mode = equals。我想要的是一个包含所有规则的完整列表,按两个属性分组,而不是硬编码值。
var regeln_empfaengertoken =
(
from rule in rules
where
(
from term in rule.Term
where
(
term.Compare_src == Entities.Enums.Compare_src.EmpfaengerToken
&&
term.Compare_mode.ToString() == "equals"
)
select term
).Count() > 0
select rule
).ToList<Entities.Rule>();
我知道这是可能的,但找不到正确的解决方案:(
[Serializable]
public class Rule
{
private List<Term> _term = new List<Term>();
...
}
[Serializable]
public class Term
{
private Entities.Enums.Compare_src _compare_src;
private Entities.Enums.Compare_mode _compare_mode;
private Entities.Enums.Compare_Type _compare_type;
.........
}
尝试这样的事情:
rules.SelectMany(rule => rule.Term)
.GroupBy(term => new { term.Compare_src, term.Compare_mode })
.Select(termGroup =>
new {
Key = termGroup.key,
Rules = rules.Where(r => r.Term.Any(t =>
t.Compare_src == termGroup.key.Compare_src &&
t.Compare_mode == termGroup.key.Compare_mode
)
}
)
我在这里所做的(无论如何都试过了,没有检查这是否真的适用于你的模型)是逆查询。 首先获取所有术语,通过多个字段键将它们分组,然后 select 为每个组的相关规则。
为什么单个组不够用? 您可以使用匿名 class 按多个术语进行分组:
var ruleGroups = from rule in rules
group by new { rule.Term.Compare_src, rule.Term.Compare_mode }
into g
select ...;
这会给你一个IGrouping
虽然你可以转换为列表列表,你可以使用SelectMany()
展平这个结构:
var orderedRuleList = ruleGroups.SelectMany( x => x)
.ToList();
不要编写只写代码。 我知道 go 对 lambda 和扩展方法的这种语法糖很有吸引力,但我建议将中间结果分配给临时持有者。
你可以试试
group term by new { term.Compare_src, term.Compare_mode }
很难确切地知道你想要什么,因为这个例子不是很清楚。 你看过这两个资源吗? MSDN和101 Linq 示例。
如果您的问题更准确,那么为您提供帮助会更容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.