C# 优化linq语句

C# 优化linq语句,c#,linq,C#,Linq,我有下面的linq声明。没有循环,我如何解决这个问题。这是一个标记系统,我只想要那些带有“myints”中ID标记的练习 根据你的查询猜一点,但是像这样 (EDIT-意识到如果找到多个匹配标记,我的第一个示例将返回重复的练习) int[]myints={1,2} ExerciseByTagId = context.ExerciseSet .Where(e => context.ItemsTags

我有下面的linq声明。没有循环,我如何解决这个问题。这是一个标记系统,我只想要那些带有“myints”中ID标记的练习


根据你的查询猜一点,但是像这样

EDIT-意识到如果找到多个匹配标记,我的第一个示例将返回重复的练习)

int[]myints={1,2}

ExerciseByTagId = 
    context.ExerciseSet
           .Where(e => context.ItemsTags
                              .Any(t=> t.ExerciseId == e.Id 
                                         && myints.Contains(t.TagsId)  
                 );

要获取列表中所有相关项目所在的项目,请执行以下操作:

int[] myints = new int[] {1,2};

var ExerciseByTagId = 
    context.ExerciseSet
    .Where(
        e => context.ItemsTags
                    .Where(t=> t.ExerciseId == e.Id) 
                    .All(t => myints.Contains(t.TagsId))  
        );
Contains()

public static bool ContainsAll<T>(this IEnumerable<T> sequence, params T[] matches)
{
    return matches.All(value => sequence.Contains(value));
}
public static bool ContainsAll(此IEnumerable序列,参数T[]匹配)
{
返回matches.All(value=>sequence.Contains(value));
}

我在一个非常类似的数据库结构上测试了它,它生成了一条SQL语句:

var selected = new [] {1,2};

var ex = from ts in context.ItemsTagsSet
         where selected.Contains(ts.TagsId)
         group ts by ts.ExerciseId into g select new
         {
            ExerciseId = g.Key,
            Count      = g.Count()
         } into x
         where x.Count == selected.Length
         join e in context.ExerciseSet on e.ExerciseId equals x.ExerciseId 
         select e;

也许我解释得有点不好,但我只想要所有标签都匹配“myints”的练习。for循环给出了这一点,但方式不好?看起来您只是在循环的每次迭代中覆盖了
ExerciseByTagId
。因此,它将始终被分配来自循环最后一次迭代的值。这将把筛选器推送到客户端而不是数据库中,因为您使用的是IEnumerable而不是IQueryable。但是没有SQL等价于
ContainsAll
函数。
var selected = new [] {1,2};

var ex = from ts in context.ItemsTagsSet
         where selected.Contains(ts.TagsId)
         group ts by ts.ExerciseId into g select new
         {
            ExerciseId = g.Key,
            Count      = g.Count()
         } into x
         where x.Count == selected.Length
         join e in context.ExerciseSet on e.ExerciseId equals x.ExerciseId 
         select e;