Search code examples
c#.netlistoopstring-comparison

Comparing attributes from a List inside a List


Description
My goal is to compare the language of a menu object from the menuList. Since the menuList has the Languages offered as another list it makes it a bit more complicated. So I tried to create a new class object with the same values so I can use menuList.Languages.Contains(languageObject), however I quickly found out that this doesn't work like that. I tried to make a for loop inside a for loop which didn't work either, but could be a failure from my side.

Obviously I can't write something like:

MenuList.Languages.Name.Equals("English").

Because of that I am looking for a solution where I can check if the attribute Name of the Languages-List inside the menuList equals a value of my choice.

The Object

private LanguageBox LangEng = new LanguageBox
{
    IsoCode = "eng",
    Name = "English"
};

The List

var MenuList = menuDataClient.GetMenuByCity(city)
    .Select(nap => new MenuBox()
    {
        Menu = nap.Menu,
        Languages = nap.Languages
            .Select(lang => new LanguageBox()
            {
                IsoCode = lang.IsoCode,
                Name = lang.Name
            }).ToList()
    })
    .ToList();

The Loop

for (int i = 0; i < MenuList.Count; i++)
{
   if (MenuList[i].Languages.Contains(LangEng))
   {
      System.Console.WriteLine("Success");
   }
}

Solution

  • I have found a solution. This LINQ option works if you want to only keep elements in the list which have English or Russian in their Languages-List.

    Solution

    .Where(lang => lang.Languages.Any(any => any.Name.Equals("English") || any.Name.Equals("Russian")))