Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use LINQ in order to select a list by matched sublist values in C#

Tags:

c#

linq

I have a class called Item:

public sealed class Item 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Language> Languages { get; set; }
}

and

public sealed class Language 
{
   public int Id { get; set; }
   public string Code { get; set; }
}

I want to get a list of Item based on a match language.

So:

string currentLangCode = "EN";
List<Item> items = GetListOfItems();

// that's not correct, I need an advice here
var query = from i in items
          where ( i.Languages.Select(l=>l).Where(l=>l.Code.Equals(currentLangCode) )
          select i;

I want to filter a list of items if their sublist (means list of languages) contains currentLanguage.

How to do that using LINQ?

like image 215
Snake Eyes Avatar asked Oct 15 '13 08:10

Snake Eyes


1 Answers

var filtered = GetListOfItems().Where(x => x.Languages.Any(l => l.Code == currentLangCode));

FYI your existing solution isn't far off, all you need to do is get rid of the unnecessary Select(...) call and you have it i.e.

var filtered = from i in GetListOfItems()
               where i.Languages.Any(l => l.Code == currentLangCode)
               select i;
like image 164
James Avatar answered Sep 28 '22 07:09

James