【发布时间】:2012-02-09 20:33:33
【问题描述】:
答案摘要:
使用 Jon Skeet 在下面的回答解决了这个问题。这是完成的代码
public static CSVData CreateCSVData(List<RegDataDisplay> rList,
string[] selectors)
{
CSVData csv = new CSVData(); // Create the CSVData object
foreach(string selector in selectors)
{
// Get the PropertyInfo for the property whose name
// is the value of selector
var property = typeof(RegDataDisplay).GetProperty(selector);
// Use LINQ to get a list of the values for the specified property
// of each RegDataDisplay object in the supplied list.
var values = rList.Select(row => property.GetValue(row, null)
.ToString());
// Create a new list with the property name to use as a header
List<string> templs = new List<string>(){selector};
// Add the returned values after the header
templs.AddRange(values);
// Add this list as a column for the CSVData object.
csv.Columns.Add(templs);
}
return csv;
}
问题
我正在根据用户输入动态构建我的 SQL 查询,然后将结果导出到 CSV 文件。我有一个名为 RegDataDisplay 的类,它对我的查询返回的每个可能的列都有一个属性。我可以知道选择了哪些列,但在我的 CSV 创建器中,我需要能够只输出那些特定的列。
在下面的示例中,我检索到的所有数据都在 rList 中,我需要的属性名称在选择器中。所以我想遍历列表,然后只将我需要的属性添加到我的 CSV 数据中。
public static CSVData CreateCSVData(List<RegDataDisplay> rList, string[] selectors)
{
CSVData csv = new CSVData();
for(int i = 0; i < selectors.Length; i++)
{
csv.Columns.Add(new List<string>(){selectors[i]});
}
// So now I have the headers for the CSV columns,
// I need the specific properties only which is where I'm stuck
for(int i = 0; i < selectors.Length; i++)
{
for(int j = 0; j < rList.Count; j++)
{
// If it was javascript I would do something like this
csv.Columns[i].Add(rList[j][selectors[i]]);
}
}
}
谢谢
编辑:现在在正确的轨道上,但我遇到了一个错误“对象与目标类型不匹配”。
public static CSVData CreateCSVData()
{
// I've created a test method with test data
string[] selectors = new string[] { "Firstname", "Lastname" };
List<RegDataDisplay> rList = new List<RegDataDisplay>();
RegDataDisplay rd = new RegDataDisplay();
rd.Firstname = "first";
rd.Lastname = "last";
rList.Add(rd);
CSVData csv = new CSVData();
foreach(string selector in selectors)
{
var property = typeof(RegDataDisplay).GetProperty(selector);
var values = rList.Select(row => property.GetValue(rList, null).ToString())
.ToList(); // Error throws here
csv.Columns.Add(values);
}
return csv;
}
【问题讨论】:
标签: c# reflection properties