优化linq语句

时间:2012-10-09 16:16:22

标签: c# linq

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

int[] myints = {1,2};
  foreach (int tagid_temp in myints)
  {
    ExerciseByTagId = 
        (from exercise in context.ExerciseSet
         where context.ItemsTagsSet
               .Where(a => a.TagsId == tagid_temp)
               .Select(a => a.ExerciseId).Contains(exercise.Id)
      select exercise);
  }

3 个答案:

答案 0 :(得分:0)

根据您的查询猜测一下,但是这样的话?

编辑 - 意识到如果找到多个匹配的代码,我的第一个示例会返回重复的练习)

<击>     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))  
        );

答案 1 :(得分:0)

Contains()非常接近您的需求,因此请使用您自己的ContainsAll()函数:

public static bool ContainsAll<T>(this IEnumerable<T> sequence, params T[] matches)
{
    return matches.All(value => sequence.Contains(value));
}

答案 2 :(得分:0)

我在一个相当类似的db结构上测试了它,它产生了一个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;