0
比方說,我有對象的這樣一個簡單的列表:LINQ的使用包含字段的名稱的字符串選擇單場
public class DataField
{
public int DataFieldId {get; set;}
public int KeyId {get; set;}
public string FieldName {get; set;}
public string Data {get; set;}
}
現在我想獲得一個屬性的值的列表使用屬性名稱的字符串值,就像這樣:
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 = "[email protected]"},
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 = "[email protected]"},
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>
包含:
「用戶名」
「電子郵件」
「PreferredContact」
我想用字符串來指定要返回的列。
+1。此外,以防萬一OP不熟悉C#中的字段與屬性區別,你提到:http://stackoverflow.com/a/295109/424129 –
我的代碼如下所示:'keys = thisSection.ReportItems.Select ('='Convert.ToString(propertyInfo.GetValue(ds)))。Distinct()。ToList();'我得到這個:Error 'System.Collections.ICollection'沒有包含'Select'並且沒有擴展方法'Select'接受'System.Collections.ICollection'類型的第一個參數可以找到(你是否缺少使用指令或程序集引用?) –
@MKenyonII'thisSection.ReportItems'的類型是什麼? –