Linq: using StringComparer with GroupBy/Distinct in query syntax

别说谁变了你拦得住时间么 提交于 2019-12-08 11:44:31

问题


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?


回答1:


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.




回答2:


var grouped = from t in doc.Descendants()
              group t by t.Element(ns + "GroupingAttr").Value into MyGroup
              select MyGroup.Key


来源:https://stackoverflow.com/questions/1047891/linq-using-stringcomparer-with-groupby-distinct-in-query-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!