Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 lsit
    }
}
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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading