c# - 如何从匿名类型中选择属性
问题描述
我有一个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;
}
解决方案
您可以像引用“普通”对象一样引用匿名类型属性:
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;
}
推荐阅读
- tensorflow - 我可以将 Tensorflow 训练的模型插入 arduino 吗?如何?
- python - IndexError:读取文本文件时列表索引超出范围
- dart - 上下文实例的颤振范围
- android - 如何根据 rgw 距离在 android 中沿一条线在 Google Maps 折线上添加标记?
- ms-word - 如何使用 Office JS API 对 word 文档的选定文本执行一些操作?
- opl - 读取文件 .txt 并将其转换为元组实例的问题
- c# - 在每行开始之前添加空格,除了字符串的第一行?
- micronaut - Micronaut 配置属性默认值
- postgresql - 从多边形列表中计算两个/四个角(东、北、西、南)
- javascript - “Home”不是 Node JS 上的构造函数