将“从对象”的归档与“项”到列表中的归档进行比较 (C#)

Compare filed from object with item into list (C#)

提问人:4est 提问时间:10/12/2022 更新时间:10/13/2022 访问量:47

问:

假设我有列名:

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.HomeselectedColumnallItems

结果应为:

string[] allItems = {name, city, createdAt};
C# .NET 比较 包含

评论

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

答:

0赞 Reza Mohammadi 10/12/2022 #1

你是说这样吗?

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

    compareString = selectedColumn.Except(allItems);
0赞 4est 10/13/2022 #2

我是这样解决的:

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();     
}