Search code examples
c#.netcomparecomparisoncontains

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


Let say I got column names:

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

Into loop from some entries I'm taking data:

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}
}

How to check if for example value car.LastName or car.Home is not in selectedColumn ? As I don't want to add this to my allItems.

Result should be:

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

Solution

  • This is how I resolve it:

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