首页 > 解决方案 > 如何从匿名类型中选择属性

问题描述

我有一个GroupBy具有多个属性的匿名类型键的表达式。我想将每个属性存储在一个单独的变量中。

当我在调试器中查看它时,items.key看起来像这样:{ Location = Halifax, Address = abc, City = abcde }.

如何将匿名类型的各个属性提取到变量中?像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; 
    }

标签: c#linqanonymous-types

解决方案


您可以像引用“普通”对象一样引用匿名类型属性:

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;
}

推荐阅读