Linq:在查询语法中使用StringComparer和GroupBy / Distinct [英] Linq: using StringComparer with GroupBy/Distinct in query syntax
问题描述
var grouped = doc我有这个(XLinq)查询并想知道如何将它转换为查询语法。 .descendants()
.GroupBy(t => t.Element(ns +GroupingAttr)。Value,StringComparer.OrdinalIgnoreCase);
这是没有StringComparer的查询语法:
var groupped =从doc.Descendants()中的t到
组t由t.Element(ns +GroupingAttr)。value分组到
select group
我的groupby比这个更复杂一点,所以我更喜欢使用组的键
这是我尝试过的,但不起作用,因为在选择的上下文中我不能使用key ve使用我更复杂的键定义来说明我不想在select中重复这个事实):
$ $ $ $ $ $ $ $ $ var变量分组=从t到doc.Descendants()
let key =((t.Name!= ns +SomeElementName)?t.Element(ns +SomeAttribute):t.Element(ns +SomeOtherAttribute ))。ElementValueOrDefault(空组)
组t通过key.ToUpper()转换为g
选择new {Name = key,Items = g};
最后,区分大小写并不重要,因为我可以假定所有的套都是一样的。 ..
相关问题: LINQ Distinct运算符忽略大小写?
我不认为您可以在查询语法中使用比较器,但是您可以打电话给ToUpper。这会让你无视案件。作为使用ToUpper的一个注意事项,比使用ToLower更有效率,所以ToUpper将是最佳选择。
C#团队非常稀疏,他们在查询中引入了什么语法,所以对于任何这样的事情,你必须使用扩展方法语法。
I have this (XLinq) query and was wondering how to convert it to the query syntax:
var grouped = doc.Descendants()
.GroupBy(t => t.Element(ns + "GroupingAttr").Value, StringComparer.OrdinalIgnoreCase);
This is the query syntax without the StringComparer:
var grouped = from t in doc.Descendants()
group t by t.Element(ns + "GroupingAttr").Value into group
select group
My groupby is a little more complicated than this, so I prefer to use the key of the group instead of introducing a new property.
This is what I tried, but doesn't work because the let "key" is not available in the context of the select (I've uses my more complicated key definition to illustrate the fact I don't want to repeat this in the select):
var grouped = from t in doc.Descendants()
let key = ((t.Name != ns + "SomeElementName") ? t.Element(ns + "SomeAttribute") : t.Element(ns + "SomeOtherAttribute")).ElementValueOrDefault("Empty group")
group t by key.ToUpper() into g
select new { Name = key, Items = g };
In the end, case-sensitivity was not important because I could presume that all casings were the same...
Related question: LINQ Distinct operator ignore case?
I don't think you can use the comparer within the query syntax, however you could call ToUpper on your value. This will then ignore case for you. As a side note using ToUpper is more efficient than using ToLower, so ToUpper would be the way to go.
The C# team were very sparse with what they introduced into the query syntax, so for anything like this you'll have to use the extension methods syntax.
这篇关于Linq:在查询语法中使用StringComparer和GroupBy / Distinct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!