【问题标题】:How to get specific properties from a list based on another list which contains properties name如何根据包含属性名称的另一个列表从列表中获取特定属性
【发布时间】:2019-04-25 05:49:58
【问题描述】:

这可能是基本概念,但我无法实现。

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

所以最后通过使用列表 A 和列表 B(我需要列表 B 中存在的属性,我需要将属性名称更改为列表 B 的 columnName。)

Final data:

 First Name | Last Name 
 John       | Smith
 Emila      | Johnson

【问题讨论】:

  • 如果您将第一个列表(详细信息)转换为数据表,然后过滤它...几乎就像您在数据库中所做的那样,您可能能够更轻松地解决它。
  • 您是否使用集合,例如 List&lt;ListA&gt; ?好像……
  • @MichałTurczyn 是的,这是我将在需要时更新的方式。
  • 所以请让您的问题更清楚,您的课程名称具有误导性......
  • @MichałTurczyn 已更新。如果现在清楚,请告诉我。

标签: c# .net c#-4.0


【解决方案1】:

尝试使用 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++;

            }

您也可以存储有关单个属性的类型信息,但是在编译时没有结构的匿名类型做任何事情将非常棘手。

【讨论】:

  • 您是否也考虑更改属性名称?
  • 不,我假设更改属性名称是指标题行。您可以在开始循环之前自行添加。在这种情况下注意二维数组长度
猜你喜欢
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
相关资源
最近更新 更多