如何合并(REMEMBER merge not combine!)这两个查询

时间:2013-10-31 13:19:53

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

我有两个linq查询:

var combo1 = from c in db.comments
             join p in db.picture on c.targetpictureid equals p.idpictures
             join u in db.users on c.iduser equals u.iduser
             select new TCommentDTO
             {
                 idcomments=c.idcomments,
                 comment1 = c.comment1,
                 targetpictureid = c.targetpictureid,
                 ctime = c.ctime,
                 iduofpic=p.iduser,
                 iduofcommentor=c.iduser,
                 profilepicofcommentor=u.profilepic,
                 usernameofcommentor=u.username,
                 picFilename=p.picFilename,
                 picTitle=p.picTitle
             };

var combo2 = from f in db.followers
             join u in db.users on f.iduser equals u.iduser
             select new TfollowerDTO
             {
                idfollowers = f.idfollowers,
                iduser = f.iduser,
                targetiduser = f.targetiduser,
                startedfollowing = f.startedfollowing,
                unoffollower = u.username,
                ppoffollower = u.profilepic,
                status = u.status
             };

我正在使用返回JSON的Web API。我想合并这两个查询的输出。

我希望以这样的方式重写此代码:评论和关注者数据应该基于ctimestartedfollowing与时间合并(不合并)。如果用户有新评论,则评论应首先出现,如果跟随者是第一个,则跟随者数据应该首先出现。我不能使用Union()和Concat(),因为首先两个类都有不同的成员,其次我不想要两个json对象都要合并。

这样的事情:

{ //comments data },
{ //follower data},
{ //comments data },
{ //comments data },
{ //comments data },
{ //follower data}

那么如何完成这项任务?

1 个答案:

答案 0 :(得分:1)

怎么样:

public class TDtoWrapper
{
    public DateTime SortKey {get;set; }
    public Object Member {get;set;}
}


var result1 = from c in combo1
              select new TDtoWrapper { SortKey = c.ctime, Member = c }

var result2 = from c in combo2
              select new TDtoWraller { SortKey = c.startedfollowing, Member = c }

var result = result1.Concat(result2).Orderby(x => x.SortKey).Select(x => x.Member);

如果您可以重写原始查询,则可以省略Dto类并编写

var combo1 = from c in db.comments
             join p in db.picture on c.targetpictureid equals p.idpictures
             join u in db.users on c.iduser equals u.iduser
             select new 
             { 
                SortKey = c.ctime, 
                Member = (object) new TCommentDTO
                {
                  idcomments=c.idcomments,
                  comment1 = c.comment1,
                  targetpictureid = c.targetpictureid,
                  ctime = c.ctime,
                  iduofpic=p.iduser,
                  iduofcommentor=c.iduser,
                  profilepicofcommentor=u.profilepic,
                  usernameofcommentor=u.username,
                  picFilename=p.picFilename,
                  picTitle=p.picTitle
                 }
             };


var combo2 = ...

var result = from c in combo1.Concat(combo2)
             orderby c.SortKey
             select c.Member;