[英]how to declare anonymous type using a variable's value as key in c#?
Is there anyway to succeed this sample? 无论如何,有没有成功的例子?
string[] columns = ["a","b","c","d"];
var headers = from column in columns
select new
{
title = column,
filter = new { column = "select" },
show = true
};
After debug this code block, I see header.filter.column
property. 调试此代码块后,我看到
header.filter.column
属性。 How can I see header.filter.a
? 我如何看到
header.filter.a
?
This is not possible, since anynonymous types are anonymous , but they still exist at compile time . 这是不可能的,因为任何匿名类型都是匿名的 ,但是它们在编译时仍然存在。 So you can not create an anonymous class with runtime member names.
因此,您不能使用运行时成员名称创建匿名类。 What you are actually doing is to set a property named
column
with the value "select"
. 您实际上正在做的是设置一个名为
column
的属性,其值为"select"
。
What you can do though is to create a dictionary from your result and access the data with the dictionary: 但是,您可以做的是根据结果创建字典并使用字典访问数据:
var headerFilterDictionary = headers.ToDictionary(item => item.title, item => item.filter.column);
var columnFilterValue = headerFilterDictionary["a"];
This probably isn't what you really want to do (at all), but you can make the syntax (mostly) work by using dynamic
: 这可能根本不是您真正想做的,但是您可以使用
dynamic
使语法(主要是)起作用:
static void Main(string[] args)
{
string[] columns = { "a", "b", "c", "d" };
var headers = from column in columns
let c_a = (dynamic)(column == "a" ? new { a = column } : null)
let c_b = (dynamic)(column == "b" ? new { b = column } : null)
let c_c = (dynamic)(column == "c" ? new { c = column } : null)
let c_d = (dynamic)(column == "d" ? new { d = column } : null)
select new
{
title = column,
filter = c_a ?? c_b ?? c_c ?? c_d,
show = true
};
var filter_0 = headers.ElementAt(0).filter.a;
var filter_1 = headers.ElementAt(1).filter.b;
var filter_2 = headers.ElementAt(2).filter.c;
var filter_3 = headers.ElementAt(3).filter.d;
}
Obviously, this doesn't scale very well; 显然,这并不能很好地扩展。 and since it's dynamic, you don't get IntelliSense on
filter
. 并且由于它是动态的,因此您不会在
filter
上获得IntelliSense。
This is probably best considered for entertainment purposes only. 最好只考虑将其用于娱乐目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.