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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With