簡體   English   中英

如何根據包含屬性名稱的另一個列表從列表中獲取特定屬性

[英]How to get specific properties from a list based on another list which contains properties name

它可能是基本概念,但我無法實現。

public class ClassA
{

    public String firstName { get; set; }
    public String lastName { get; set; }
    public int employeeID{ get; set; }
    public decimal salary { get; set; }
}

data in List A = List<ClassA> :

 firstName | lastName |employeeID | salary
 John      | Smith    | 123       |$400
 Emila     | Johnson  | 124       |$500

我想根據列表B中的數據從列表A中選擇一些屬性。

public class ClassB
{

    public String column{ get; set; }
    public String coulmnName{ get; set; }
}

data in List B  = List<ClassB> 

     column   | coulmnName
    firstName | First Name
    lastName  | Last Name

所以最后使用List A和List B(我需要列表B中存在的屬性,我需要將屬性名稱更改為List B的columnName。)

Final data:

 First Name | Last Name 
 John       | Smith
 Emila      | Johnson

嘗試使用linq會很棘手,因為您不知道在編譯時要選擇的所有屬性。

解決方法是捕獲二維數組中的所有屬性:

public class Item
{
    public String firstName { get; set; }
    public String lastName { get; set; }
    public int employeeID { get; set; }
    public decimal salary { get; set; }
}

public class Filter
{
    public String PropertyName { get; set; }
    public String PropertyValue { get; set; }
}

private string GetPropertyValue(Item item, string propertyName)
{
    return item.GetType().GetProperty(propertyName).GetValue(item, null).ToString();
}

而實際的代碼是:

            List<Item> items = new List<Item>();
            items = CreateData(items); // fill with dummy items
            List<Filter> filters = new List<Filter>();
            filters = CreateFilter(filters); // fill with dummy items
            string[,] target = new string[items.Count,filters.Count];

            int row = 0, col = 0;
            foreach (var item in items)
            {
                foreach (var filter in filters)
                {
                    target[row, col] = GetPropertyValue(item, filter.PropertyName);
                    row++;
                }
                row = 0;
                col++;

            }

您也可以存儲有關各個屬性的類型信息,但是在編譯時沒有結構的匿名類型中執行任何操作都會非常棘手。

暫無
暫無

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

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