簡體   English   中英

Linq使用包含字段名稱的字符串選擇單個字段

[英]Linq select a single field using a string containing the name of the field

假設我有一個簡單的對象列表,如下所示:

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 = "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>
“用戶名”
“電子郵件”
“PreferredContact”

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

您可以使用反射。 您使用的是“字段”,但該類實際上包含屬性,因此請使用反射的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/zh-cn/library/system.reflection.propertyinfo(v=vs.110).aspx

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM