-3

我有这两个 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}

那么如何完成这个任务呢?

4

1 回答 1

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;
于 2013-10-31T13:38:47.527 回答