在linq中组合两个查询



我有两个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());

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

您可以直接将其传递给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有点生锈),但无论如何你都没有这样做,所以效果与你的相同。如果它能够组合,那么这样您将获得更有效的执行。

如果您不介意混合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());

相关内容

  • 没有找到相关文章

最新更新