VB中的LINQ C#查询 - 出错

时间:2012-02-22 17:09:26

标签: c# vb.net linq

我有一个价格对象列表(价格包含日期,高,低),我试图通过LINQ提取月平均值。我在C#中工作但是我们在VB.Net中有一些需要它的遗留应用程序,我似乎无法弄清楚转换。我甚至试过把它分成两个查询都无济于事。

工作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),
    };

尝试VB翻译

 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) _
        }

收到错误:

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

不太清楚从哪里开始。我尝试了一些在线C# - > VB.Net Translators,但他们对我帮助不大。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我认为你放Select代替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) _
    }

答案 1 :(得分:1)

VB在此类查询中的优势之一是在Group By语句中轻松声明范围变量。无论如何,这是一个可能的VB翻译:

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) _
            }