【问题标题】:Compare filed from object with item into list (C#)将对象中的字段与列表中的项目进行比较(C#)
【发布时间】:2022-10-13 18:18:40
【问题描述】:

假设我有列名:

IList<string> selectedColumn = new List<string>{"Name", "City", "CreatedAt"};

从一些条目进入循环,我正在获取数据:

foreach (Car car in rowsWithAllCar)
{
 string name = car.Name;
 string lastName = car.LastName;
 string city = car.City;
 string home = car.Home;     
 DateTime createdAt= (DateTime)car.CreatedAt;

 string[] allItems = {name, lastName, phone, city, createdAt}
}

如何检查例如值 car.LastNamecar.Home 是否不在 selectedColumn 中?因为我不想将此添加到我的allItems

结果应该是:

string[] allItems = {name, city, createdAt};

【问题讨论】:

  • 您的示例根本不会产生任何结果,因为它只是声明了一个仅在循环内有效的本地 allItems 数组。这使得很难理解实际意图是什么。如果您只想检查列表是否包含值,则有List.Contains

标签: c# .net compare comparison contains


【解决方案1】:

这是你想做的吗?

IList<string> selectedColumn = new List<string> { "Name", "City", "CreatedAt" };

foreach (Car car in rowsWithAllCar)
{
    var properties = car.GetType().GetProperties();
    var allItems = properties
        .Where(p => selectedColumn.Contains(p.Name))
        .Select(p => p.GetValue(car))
        .Cast<string>()
        .ToArray();

    //string name = car.Name;
    //string lastName = car.LastName;
    //string city = car.City;
    //string home = car.Home;
    //DateTime createdAt = (DateTime)car.CreatedAt;

    //string[] allItems = { name, lastName, phone, city, createdAt };
}

我评论了你的代码。

【讨论】:

  • 我试过但没有用,我找到了其他解决方案,请检查我的答案
【解决方案2】:

你的意思是这样的吗?

    List<string> compareString = new List<string>();

    compareString = selectedColumn.Except(allItems);

【讨论】:

    【解决方案3】:

    这就是我解决它的方法:

    foreach (Car car in rowsWithAllCar)
    {
    IDictionary<string, string> carFields = new Dictionary<string ,string>();
     string name = car.Name;
     carFields.Add("Name", name);
     
     string lastName = car.LastName;
     carFields.Add("LastName", lastName);
     
     string city = car.City;
     carFields.Add("City", city);
     ...
     IList<string> allItems = new List<string>();
    
       foreach (var carField in carFields)
       {
           bool isInSelectedColumn = selectedColumn.Contains(carField.Key);
           
           if (isInSelectedColumn)
           {
             allItems.Add(carField.Value);
           }
       }
       //allItems.ToArray();     
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 2018-09-10
      • 2011-08-18
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多