LINQ VB how to select records with the max date (highest date)

19,436

Solution 1

Here's an example from MSDN of grouping in VB:

Dim query = From p In db.Products _
            Group p By p.CategoryID Into g = Group _
            Select CategoryID, MaxPrice = g.Max(Function(p) p.UnitPrice)

If you omit the "= Group", it will consider g as a function. Hope this helps.

Solution 2

Dim q = From n In table _
        Group n By n.AccountId Into g _
        Select g.OrderByDescending(Function(t) t.Date).First() 
Share:
19,436

Related videos on Youtube

Watki02
Author by

Watki02

I am a network engineer (ex-VB & C# .Net Programmer) in Columbus, OH. I enjoy researching problems, learning about new technologies, thinking about software architecture, looking for loopholes (in any system, not just I.T.), doing things better/faster, and seeing systems built and functioning. I also have a secret passion: Physics. While only a hobby right now, I someday hope to go back to school to finish a degree in physics.

Updated on April 15, 2022

Comments

  • Watki02
    Watki02 about 2 years

    I know how to do this in C#, but my dev team doesn't use C#...

    here is the answer in C#: How to select only the records with the highest date in LINQ

    How do I do this in VB?

    Essentially, if I knew how to write lambda expressions in VB, I would be set, but the materials I have found are not helpful.

    I also need to know why the Into identifier (i.e. "g") is always trying to be a function every time I move off the line, resulting in this error:

    http://img19.imageshack.us/i/errno.png/

  • Watki02
    Watki02 over 14 years
    as I put that into my code, the pre-compiler (I think) keeps turning "g" into "g()" as soon as I move off the line, thus throwing an error. It thinks g needs be a function ??
  • Watki02
    Watki02 over 14 years
    this code does not work. "g" is not an acceptable "groupname"
  • tsuo euoy
    tsuo euoy over 14 years
    @Joel: There's still a problem with the group Into g which doesn't work in VB.
  • Watki02
    Watki02 over 14 years
    That actually just confuses the compiler. "Group" is a key word. The environment keeps trying to add "()" after "g", like it is supposed to be a function. I am wondering if that is because this code is in an event handler in a class (don't know why that would make a difference), or if it is because I might have an outdated version of the framework? All I know is that it doesn't work as is.
  • tsuo euoy
    tsuo euoy over 14 years
    Did you try it with Group? You could also try "Group n By n.AccountId Into g = Group"...