0

我有下面的 linq 语句。没有循环我怎么能解决这个问题。这是一个标签系统,我只想要那些在“myints”中具有带有 ids 的标签的练习

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);
  }
4

3 回答 3

0

我在一个非常相似的数据库结构上测试了它,它产生了一个 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;
于 2012-10-09T20:24:40.537 回答
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))  
        );
于 2012-10-09T16:24:53.337 回答
0

Contains()is pretty close to what you need, so use your own ContainsAll() function:

public static bool ContainsAll<T>(this IEnumerable<T> sequence, params T[] matches)
{
    return matches.All(value => sequence.Contains(value));
}
于 2012-10-09T17:08:50.517 回答