views:

471

answers:

2

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?

A: 
var grouped = from t in doc.Descendants()
              group t by t.Element(ns + "GroupingAttr").Value into MyGroup
              select MyGroup.Key
Rony
I don't see what you're selecting know? I do not only need the keys, hence I would use a Distinct.
riezebosch
A: 

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.

DoctaJonez
I didn't want to use the ToUpper because I need the Key later on and don't want them to be all uppercase. As stated before, I could probably create an anonymous type and define a property with the samen value as the key but use the original value. I didn't want to do that because my key is quite complicated but I can use a let in this case...
riezebosch
In this case I'd stick with the non query syntax then.
DoctaJonez
Although if you used ToUpper only the grouping key would be the uppercase version of the key, the actual key stored within the object would still be the original version of the key.
DoctaJonez
I've update my original question to illustrate my findings (with regard to using 'let').
riezebosch