5

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?

4

1 回答 1

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

仅供参考,您现有的解决方案并不遥远,您需要做的就是摆脱不必要的Select(...)呼叫,您就拥有了,即

var filtered = from i in GetListOfItems()
               where i.Languages.Any(l => l.Code == currentLangCode)
               select i;
于 2013-10-15T08:39:37.570 回答