在一个查询中收集两个linq查询

时间:2015-03-23 13:07:31

标签: c# asp.net linq entity-framework linq-to-sql

我有以下实体框架方法

maList = (from p in db.full
                  where (p.mc_object.Contains(str))
                  group p by p.mc_object into g
                  orderby g.Count() descending
                  select new StringIntType
                  {
                      str = g.Key,
                      nbr = g.Count(),
                      par="object"
                  }).ToList();

maList = (from p in db.full
                  where (p.mc_owner.Contains(str))
                  group p by p.mc_owner into g
                  orderby g.Count() descending
                  select new StringIntType
                  {
                      str = g.Key,
                      nbr = g.Count(),
                      par="owner"
                  }).ToList();

我想在一个查询中制作它们。

2 个答案:

答案 0 :(得分:3)

您可以使用Concat

var objects = from p in db.full
              where (p.mc_object.Contains(str))
              group p by p.mc_object into g
              orderby g.Count() descending
              select new StringIntType
              {
                  str = g.Key,
                  nbr = g.Count(),
                  par="object"
              };

var owner = from p in db.full
            where (p.mc_owner.Contains(str))
            group p by p.mc_owner into g
            orderby g.Count() descending
            select new StringIntType
            {
                str = g.Key,
                nbr = g.Count(),
                par="owner"
            };

maList = objects.Concat(owner).ToList();

这看起来不像一个查询,但由于LINQ的延迟执行,只有一个查询被发送到ToList()的数据库。

答案 1 :(得分:0)

您可以使用Union方法

maList = (from p in db.full
              where (p.mc_object.Contains(str))
              group p by p.mc_object into g
              orderby g.Count() descending
              select new StringIntType
              {
                  str = g.Key,
                  nbr = g.Count(),
                  par="object"
              })
              .Union(from p in db.full
              where (p.mc_owner.Contains(str))
              group p by p.mc_owner into g
              orderby g.Count() descending
              select new StringIntType
              {
                  str = g.Key,
                  nbr = g.Count(),
                  par="owner"
              }).ToList();