在linq中组合两个查询

时间:2014-03-29 10:56:56

标签: sql linq entity-framework

我有两个linq查询如下:

GroupNamesWithCorrespondingEffects 
        = new ObservableCollection<GroupNameWithCorrespondingEffect>(
                                  from g in db.Groups
                                  select new GroupNameWithCorrespondingEffect
                                                {
                                                    GroupID = g.GroupID,
                                                    GroupName = g.GroupName,
                                                    CorrespondingEffect = g.Master_Effects.Effect

                                                }
                                         );

 GroupNamesWithCorrespondingEffects 
          = new ObservableCollection<GroupNameWithCorrespondingEffect>       
                       (GroupNamesWithCorrespondingEffects.
                            Where(u => !GetAllChildren(25).
                                        Select(x => x.GroupID).
                                        Contains(u.GroupID)).ToList());

现在我该如何组合这两个查询?

2 个答案:

答案 0 :(得分:1)

您可以直接将其传递给ObservableCollection

的构造函数
from g in groups
let g = select new GroupNameWithCorrespondingEffect
        { 
            GroupID = g.GroupID,
            GroupName = g.GroupName,
            CorrespondingEffect = g.Master_Effects.Effect
        }
where !GetAllChildren(25)
       .Select(x => x.GroupID)
       .Contains(g.GroupID)
select g

我不确定EF是否能够编写第一部分和第二部分(如果在Contains条款中解析了IN,我就不记得了。 EF有点生疏,但你还是没有这样做,所以效果和你的一样。如果它能够编写,那么这样你就可以更有效地执行。

答案 1 :(得分:0)

如果您不介意混合SQL样式和扩展方法语法,可以这样做:

GroupNamesWithCorrespondingEffects 
        = new ObservableCollection<GroupNameWithCorrespondingEffect>(
                (from g in groups
                 select new GroupNameWithCorrespondingEffect
                     { GroupID = g.GroupID,
                       GroupName = g.GroupName,
                       CorrespondingEffect = g.Master_Effects.Effect
                     })
                 .Where(u => !GetAllChildren(25)
                        .Select(x => x.GroupID)
                        .Contains(u.GroupID))
                 .ToList());