Willy
Willy

Reputation: 10650

Translating LINQ expression from C# into VB.NET throws exception in Group by

I have below Linq expresion in C# and it is working perfectly:

from c3 in equipment.Measures
where c3.IdEq == eq.IdEq && !(c3.magnitudeId == null || c3.magnitudeId.Trim() == string.Empty)
group c3 by c3.magnitudeId into cgroup
                  select new
                  {
                      MagnitudeID = cgroup.Key,
                      MaxDate = cgroup.Max(x => x.NextDate)
                  }

Now I am trying to convert it into VB.NET notation:

From c3 In equipment.Measures
Where c3.IdEq = eq.IdEq AndAlso Not (String.IsNullOrWhiteSpace(c3.magnitudeId))
Group c3 By c3.magnitudeId Into grp = Group
          Select New With
          {
            .MagnitudeID = grp.Key,
            .MaxDate = grp.Max(Function(x) x.NextDate)
          }

... but I get an error message saying:

'key' is not a member of 'System.Collection.Generics.IEnumberable(Of ...)'

Upvotes: 2

Views: 107

Answers (3)

Andrew Morton
Andrew Morton

Reputation: 25057

If you use the other way (method syntax) of writing LINQ, it works (more closely to) the same way as in C#:

Dim q = (equipment.Measures).
    Where(Function(a) a.IdEq = eq.IdEq AndAlso Not String.IsNullOrWhiteSpace(a.MagnitudeID)).
    GroupBy(Function(b) b.magnitudeId).
    Select(Function(c) New With {Key .MagnitudeID = c.Key, Key .MaxDate = c.Max(Function(x) x.NextDate)})

Upvotes: 1

Dave Doknjas
Dave Doknjas

Reputation: 6542

Try the following (and also note that to be equivalent you need the 'Key' keyword in VB):

From c3 In equipment.Measures
    Where c3.IdEq = eq.IdEq AndAlso Not (c3.magnitudeId Is Nothing OrElse c3.magnitudeId.Trim() = String.Empty)
    Group c3 By c3.magnitudeId Into cgroup = Group
    Select New With {
        Key .MagnitudeID = magnitudeId,
        Key .MaxDate = cgroup.Max(Function(x) x.NextDate)
    }

It would be nice if the C# and VB teams had coordinated a bit since some of the differences in LINQ between C# and VB are very puzzling.

Upvotes: 2

djv
djv

Reputation: 15774

Use Group instead of a named group

From c3 In equipment.Measures
Where c3.IdEq = eq.IdEq AndAlso Not (c3.magnitudeId = Nothing OrElse c3.magnitudeId.Trim() = String.Empty)
Group c3 By c3.magnitudeId Into Group
Select New With
{
    Group.First().magnitudeId,
    .MaxDate = Group.Max(Function(x) x.NextDate)
}

Upvotes: 1

Related Questions