Home > Software design >  How to pass an anonymous type to a function, then get the values
How to pass an anonymous type to a function, then get the values

Time:01-28

I have a function like this:

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

I am generating a Grouping like this:

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());

I would like to pass gb to DropIncompleteQuarters, but I am not sure what the type should be.

Then inside of DropIncompleteQuarters, I would like to iterate over the items?

CodePudding user response:

I suggest using named tuple instead of anonymous type. With a slight syntax change - (...) instead of {...} you can put

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());
  • Related