Linq: using StringComparer with GroupBy/Distinct i

2019-06-09 14:28发布

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?

2条回答
霸刀☆藐视天下
2楼-- · 2019-06-09 14:42
var grouped = from t in doc.Descendants()
              group t by t.Element(ns + "GroupingAttr").Value into MyGroup
              select MyGroup.Key
查看更多
闹够了就滚
3楼-- · 2019-06-09 14:43

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.

查看更多
登录 后发表回答