[英]How to Iterate through IEnumerable with Unknown Properties
I have an many different IEnumerable<T>
's that have numerous properties of various types. 我有许多不同的
IEnumerable<T>
,它们具有各种类型的许多属性。 I would like to be able to iterate through each property under the IEnumerable. 我希望能够遍历IEnumerable下的每个属性。
Example Idea: 示例示例:
var data = someSource.First();
data.ForEach(o => DoStuff(o));
Unfortunately I cannot find a way to do this, currently I am having to know the name of the property to be able to access it. 不幸的是,我找不到一种方法来执行此操作,当前我必须知道该属性的名称才能访问它。
Any help would be greatly appreciated. 任何帮助将不胜感激。
Further Clarification: I am using ADO.NET/Entity Framework with MySQL, I have a MySQL Database Table with the following format: http://pastebin.com/P51hURaj 进一步说明:我将ADO.NET/Entity Framework与MySQL配合使用,我有一个具有以下格式的MySQL数据库表: http : //pastebin.com/P51hURaj
It consists of 60 Labels and 60 Types for those Labels. 它由60个标签和这些标签的60种类型组成。
using (var connection = new hyperion_collectionsmaxEntities())
{
var customs = connection.customs.First();
//connection.customs is a DbSet<custom>
//custom is defined as: http://pastebin.com/XW8pfzbD
//Need to Iterate through Customs, Ex:
//var custom1 = customs.label1; Through 60!?
}
I need to output all 60 customs into a ListBox via AddStatus(custom*); 我需要通过AddStatus(custom *)将所有60个海关输出到ListBox中;
I strongly question the intended use here, but to answer the question as it is specifically, you can use reflection to grab each property of each object: 我强烈质疑这里的预期用途,但是要具体回答这个问题,您可以使用反射来获取每个对象的每个属性:
var propertyValues = someSource.SelectMany(obj => obj.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => p.GetValue(obj)));
foreach(var propertyValue in propertyValues)
DoStuff(propertyValue);
Or to be more LINQ-ey like in your question: 或者更像LINQ-ey在您的问题中:
someSource.SelectMany(obj => obj.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Select(p => p.GetValue(obj)))
.ToList()
.ForEach(o => DoStuff(o));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.