簡體   English   中英

如何結合這兩個linq查詢的輸出?

[英]How to combine the output of these two linq queries?

我想結合這兩個查詢的輸出,combo1和combo2。 到目前為止,我能夠編寫如下代碼:

        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


                    };

        var resultantcombo =combo1.Union(combo2);
        return resultantcombo;

但是在我執行工會的第二行,我收到了這些錯誤:

錯誤1無法將類型'System.Collections.Generic.IEnumerable'隱式轉換為'System.Linq.IQueryable'。 存在顯式轉換(您是否錯過了演員?)

錯誤2實例參數:無法從>'System.Linq.IQueryable'轉換為>'System.Linq.ParallelQuery'

錯誤3'System.Linq.IQueryable'不包含'Union'的定義和最佳擴展方法重載'System.Linq.ParallelEnumerable.Union(System.Linq.ParallelQuery,System.Collections.Generic.IEnumerable)'有一些無效的參數

哪里我錯了,我該怎么做才能成功地結合這兩個查詢?

您可以返回匿名類型:

return Json(new {
    Comments = combo1,
    Followers = combo2
});

如果要將它們作為方法中的參數傳遞,則應創建一個包含兩個集合作為屬性的類:

public class CommentsAndFollowersDTO
{
    public IEnumerable<TCommentDTO> Comments { get; set; }

    public IEnumerable<TfollowerDTO> Followers { get; set; }
}

我不認為你可以聯合兩種不同類型的集合。 您始終可以將這兩個查詢加入到一個匿名對象中,就像這樣

var q = from c1 in combo1
        from c2 in combo2
        select new { 
            Comments = c1,
            Followers = c2
        }

我不確定你想要的輸出是什么,但是如果你不打算創建一個帶有屬性的新類來保存兩個列表,這種方式就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM