如何将匿名类型传递给函数,然后获取值

How to pass an anonymous type to a function, then get the values

提问人:Ivan 提问时间:1/28/2023 更新时间:1/28/2023 访问量:55

问:

我有一个这样的:function

private void DropIncompleteQuarters(//what goes in here? This? IEnumerable<dynamic> gb)
{
    foreach(var groupInGb in gb)
    {
        // What goes in here to get each element?
    }
}

我正在生成这样的:Grouping

histData = new List<OHLC>();

var gb = histData.GroupBy(o => new
{
    Year = o.Date.Year,
    Quarter = ((o.Date.Month - 1) / 3) + 1
})
.ToDictionary(g => g.Key, g => g.ToList());

我想传递给 ,但我不确定应该是什么。gbDropIncompleteQuarterstype

那么在里面,我想迭代一下?DropIncompleteQuartersitems

C# 动态 分组 匿名类型

评论


答:

5赞 Dmitry Bychenko 1/28/2023 #1

我建议使用命名元组而不是匿名类型。稍微改变一下语法 - 而不是你可以把(...){...}

private void DropIncompleteQuarters(Dictionary<(int Year, int Quarter), 
                                               List<OHLC>> gb)
{
    foreach (var pair in gb)
    {
        // Let's deconstruct pair.Key 
        var (year, quarter) = pair.Key; 
        var list = pair.Value;

        //TODO: some logic for year and quarter and list
    }
}
histData = new List<OHLC>();

var gb = histData
   .GroupBy(o => ( // change { .. } to ( .. ) and `=` to `:`
      Year    : o.Date.Year,
      Quarter : ((o.Date.Month - 1) / 3) + 1
   ))
   .ToDictionary(g => g.Key, g => g.ToList());

评论

0赞 Dmitry Bychenko 1/28/2023
@Ivan:我明白了;你把整本字典传给 ;然后让我们更改其签名。我已经编辑了答案。DropIncompleteQuarters