2013-10-31 115 views
-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 
      }; 

我使用的Web API返回JSON。我想合併這兩個查詢的輸出。

我想以這樣一種方式重寫這段代碼,即基於ctimestartedfollowing,評論和跟隨者數據應該根據時間合併(未合併)。如果用戶有新的評論,評論應該是第一,如果跟隨者是第一,跟隨者的數據應該是第一位。我不能使用Union()和Concat(),因爲首先兩個類有不同的成員,其次我不想兩個json對象進行組合。

事情是這樣的:

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

那麼如何做這個任務?

+0

你知道'聯盟()'? – gunr2171

+0

是的,我知道Union()和Concat(),但不能使用它們,因爲首先兩個類都有不同的成員,其次我不希望將兩個json對象合併。 – Obvious

+0

這聽起來像你必須[完全外部連接](http://stackoverflow.com/q/2085422/1043380)你的兩個查詢,但我不知道。 – gunr2171

回答

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); 

,如果你可以重寫origninal查詢,可以ommit的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; 
+0

我認爲你已經到達那裏,讓我試試吧...... – Obvious

+0

我得到這個錯誤,同時實施你的解決方案,不能隱式轉換類型'System.Linq.IQueryable '到'System.Linq .IQueryable 」。一個顯式的轉換存在(你是否缺少一個轉換?) – Obvious

+0

解決了,現在得到一個運行時錯誤:DbUnionAllExpression需要兼容集合的參數ResultTypes – Obvious