Emi
Emi

Reputation: 306

Use query syntax in GroupBy with complex range variable

I have a LINQ query, where I want to group elements from a collection. I'm trying to use query syntax to achieve my result, but I can't figure out how to describe a more complex range variable using query syntax.

Using method syntax, this works:

Dim R = someCollection.GroupBy(Function(x)
                                       For Each cItem In x.Attributes
                                           If cItem.Name = "N1" Then Return cItem.Value
                                       Next
                                   End Function)

I tried doing this in query syntax, but failed. So this doesn't work and gives an error: Range variable name can be inferred only from a simple or qualified name with no arguments.

Dim R = From q In someCollection
            Group q By Function(x)
                           For Each cItem In q.Attributes
                               If cItem .Name = "N1" Then Return cItem .Value
                           Next
                       End Function
                Into Group

I tried various other versions, but to no avail. How can I group by a complex parameter using a query syntax? Or should just stick to method syntax?

Upvotes: 0

Views: 60

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54457

A For Each loop that exits the first time a condition is satisfied can generally be collapsed into a single call to First, FirstOrDefault, Single or SingleOrDefault. In this case, the best option depends on whether there will always be one match or there can be none or more than one.

Always one: Single Never more than one: SingleOrDefault Never less than one: First None, one or many: FirstOrDefault

In this case, assuming the last case:

Group q By q.Attributes.FirstOrDefault(Function(a) a.Name = "N1")?.Value

Null propagation is used because the "OrDefault" means that Nothing may be returned.

Upvotes: 1

Related Questions