Using the ALL operator in linq to filter child items of EntitySet

前端 未结 2 2000
你的背包
你的背包 2020-12-21 19:25

I have a two objects as follows:

public class Item
{
    public int ItemId {get;set;}
    public string ItemName {get;set;}
    public List ItemTa         


        
2条回答
  •  醉酒成梦
    2020-12-21 19:43

    That because you're puting the tags from the items to lowercase, but not the searched tags.

    With this modification it should work:

    List tagsList = tags
        .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(s => s.ToLower())
        .Distinct()
        .ToList();
    

    EDIT: OK, I see what the problem is: you're doing it backwards. You're searching for items that have only the tags that you're looking for.

    Try that instead:

    query = 
        (from item in query
         let itemTags = p.ItemTags.Select(it => it.TagName.ToLower())
         where tags.All(t => itemTags.Contains(t))
         select item).ToList();
    

    UPDATE: here's a version with the lambda syntax. It's pretty ugly because of the temporary anonymous type, but that's how the let clause translates to lambda...

    query =
        query.Select(item => new { item, itemTags = item.ItemTags.Select(it => it.TagName.ToLower()) })
             .Where(x => tagsList.All(t => x.itemTags.Contains(t)))
             .Select(x => x.item)
             .ToList();
    

提交回复
热议问题