2016-01-11 58 views
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」

我想用字符串來指定要返回的列。

回答

4

您可以使用反射。您正在使用「字段」,但該類實際上包含屬性,因此請使用反射的方法GetProperty()。如果您使用的字段,而應使用GetField()

public static List<string> getFieldData(List<DataField> dataToSearch, string fieldName) 
{ 
    // You can use reflection to get information from types at runtime. 
    // The property_info variable will hold various data about the field 
    // name you pass in (type, name, etc) 
    var property_info = typeof(DataField).GetProperty(fieldName); 

    // We can then call property_info's GetValue() on an instantiated 
    // object of our class, and it will return the value of that property on that object 
    return dataToSearch.Select(ds => Convert.ToString(property_info.GetValue(ds))).Distinct().ToList(); 
} 

的PropertyInfo類:https://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo(v=vs.110).aspx

Type類:https://msdn.microsoft.com/en-us/library/system.type(v=vs.110).aspx

+3

+1。此外,以防萬一OP不熟悉C#中的字段與屬性區別,你提到:http://stackoverflow.com/a/295109/424129 –

+0

我的代碼如下所示:'keys = thisSection.ReportItems.Select ('='Convert.ToString(propertyInfo.GetValue(ds)))。Distinct()。ToList();'我得到這個:Error 'System.Collections.ICollection'沒有包含'Select'並且沒有擴展方法'Select'接受'System.Collections.ICollection'類型的第一個參數可以找到(你是否缺少使用指令或程序集引用?) –

+0

@MKenyonII'thisSection.ReportItems'的類型是什麼? –

相關問題