假设我有一个简单的对象列表,如下所示:
public class DataField
{
public int DataFieldId {get; set;}
public int KeyId {get; set;}
public string FieldName {get; set;}
public string Data {get; set;}
}
现在我想使用Property名称的字符串值获取Property中的值列表,如下所示:
public List<string> getFieldData(List<DataField> dataToSearch, string propertyName)
{
// This is the area I'd like to figure out.
return dataToSearch.Select(ds => ds.propertyName).Distinct.ToList();
}
public void MyMethod()
{
var data = new List<DataField>{
new DataField{DataFieldId = 1, KeyId = 1,
FieldName = "UserName", Data = "jSmith"},
new DataField{DataFieldId = 2, KeyId = 1,
FieldName = "Email", Data = "jSmith@nowhere.com"},
new DataField{DataFieldId = 3, KeyId = 1,
FieldName = "PreferredContact", Data = "Phone"},
new DataField{DataFieldId = 4, KeyId = 2,
FieldName = "UserName", Data = "jDoe"},
new DataField{DataFieldId = 5,KeyId = 2,
FieldName = "Email", Data = "janeDoe@emailServer.net"},
new DataField{DataFieldId = 6, KeyId = 2,
FieldName = "PreferredContact", Data = "Email"}
};
// Notice I want to search using a string
var fieldNames = getFieldData(data, "FieldName");
}
我希望fieldNames是 List<string>
包含:
"UserName"
"Email"
"PreferredContact"
我想使用一个字符串来指定要返回的列 .
1 回答
你可以使用反射 . 你're using 2441852 but the class actually contains properties, so use reflection' s
GetProperty()
方法 . 如果您改用字段,请使用GetField()
PropertyInfo类:https://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo(v=vs.110).aspx
输入类:https://msdn.microsoft.com/en-us/library/system.type(v=vs.110).aspx