Panmother
Panmother

Reputation: 487

LINQ C# query in VB - getting an error

I have a List of Price Objects (Price contains Date, High, Low) and am trying to extract monthly averages via LINQ. I have this working in C# but we have a few legacy applications that need it in VB.Net and I can't quite seem to figure out the conversion. I've even tried breaking it into two queries to no avail.

Working C#

var prices = from allData in priceList
    group allData by new { month = allData.Date.Month, year = allData.Date.Year } into grp
    select new
    {
        Month = grp.Key.month,
        Year = grp.Key.year,
        AvgHigh = grp.Average(c => c.High),
    };

Attempted VB translation

 dim GroupList = From allData In priceList SELECT New With 
            { _
                .month = allData.Date.Month, _
                .year = allData.Date.Year 
            }

        Dim prices = From grp in GroupList _
        SELECT New With { _
                .Month = grp.month, _
                .Year = grp.year, _
                .AvgHigh = grp.Average(function(c) c.High) _
        }

Error received:

 BC36610: Name 'Average' is either not declared or not in the current scope.

Not quite sure where to proceed from here. I've tried a few online C# -> VB.Net Translators, but they aren't helping me much. Any ideas?

Upvotes: 2

Views: 571

Answers (2)

diceguyd30
diceguyd30

Reputation: 2752

One of VB's strengths in queries like this is the ease of declaring range variables in Group By statements. At any rate, here is one possible VB translation:

Dim prices = From allData In priceList _
             Group allData By Month = allData.[Date].Month, Year = allData.[Date].Year Into Group _
             Select New With { _
                .Month = Month, _
                .Year = Year, _
                .AvgHigh = Group.Average(Function(c) c.High) _
            }

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

I think you put Select instead of Group allData By:

Dim prices = From allData In priceList
    Group allData By New With { _
        Key .month = allData.[Date].Month, _
        Key .year = allData.[Date].Year _
    }
    Select New With { _
        Key .Month = grp.Key.month, _
        Key .Year = grp.Key.year, _
        Key .AvgHigh = grp.Average(Function(c) c.High) _
    }

Upvotes: 1

Related Questions