0

I have a GroupBy expression that has an anonymous type key with more than one property. I would like to store each property in a separate variable.

When I look at it in the debugger, items.key looks like this: { Location = Halifax, Address = abc, City = abcde }.

How would I extract the individual properties of the anonymous type into a variable? Something like var foo = items.key[Location] ?

   private class ReportItem
    {
        public string Location { get; set; }
        public string City { get; set; }
        public string Address { get; set; }
        public string UserName { get; set; }
        public string QA { get; set; }
    }
---
    finalReportList.Add(new ReportItem
    {
        Location = location,
        City = city,
        Address = address,
        UserName = name,
        QA = qa                        
    }); 

    var testquery = finalReportList.GroupBy(x => new {x.Location, x.City, x.Address});

    foreach (var items in testquery)
    {
        
        var location = items.Key; 
    }
HJ1990
  • 385
  • 1
  • 4
  • 19
  • `items.Key` is not a lambda expression, it is an anonymous type object. Why does your comment not match your `GroupBy`? – NetMage Oct 06 '20 at 21:32

1 Answers1

1

You can reference anonymous type properties just as you would a "normal" object:

var testquery = finalReportList.GroupBy(x => new { x.Location, x.City, x.Address });

foreach (var item in testquery)
{
    var location = item.Key.Location;
    var city = item.Key.City;
    var address = item.Key.Address;
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43