加入,分组和linq的位置

时间:2013-12-12 19:09:14

标签: c# linq join group-by

我有三张桌子:

  
      
  • 请求(requestId,userId,languageId,text,timePosted)
  •   
  • RequestLanguages(requestId,languageId)
  •   
  • UserLanguages(userId,languageId) - 用户知道的所有语言
  •   

In Requests languageId是询问请求的语言,但在RequestLanguages中,lan​​guageId是用户想要翻译的语言。用户想要翻译的语言很少,而不仅仅是一种语言。

我需要在Linq中进行查询,我将在其中选择用户知道想要翻译的语言的所有请求,用户也知道(需要是列表)。

我使用了group by但我并不擅长这个。我不知道如何在requestId上加入请求和RequestLanguages并将所有languageId用户想要翻译成列表!

我试过这样的事情:

using (var context = new WordsEntities())
        {
            List<short> languagesIKnow = (from ul in context.UserLanguages
                                          where ul.userId == userId
                                          select ul.languageId).ToList();

            var requests = (from rl in context.RequestLanguages
                            group rl.languageId by rl.requestId into p
                            select new
                            {
                                languageTold = p.ToList(),
                                reqId = p.Key
                            }
                            );
            List<ShowRequests> list = new List<ShowRequests>();
            foreach (var r in requests)
            {
                ShowRequests Req = from req in context.Requests
                          where req.requestId == r.reqId
                          && languagesIKnow.Exists(y => y == req.languageId)
                          && languagesIKnow.Intersect(r.languageTold).Any()
                          select new ShowRequests
                          {
                              languageAsk = req.languageId,
                              languageTold = r.languageTold,
                              userId = req.userId,
                              text = req.text,
                              picture = req.pictureExtension,
                              audio = req.audioExtension,
                              timePosted = req.timePosted
                          };
                list.Add(Req);



            }

但我无法将Req指定为类ShowRequests ..

2 个答案:

答案 0 :(得分:1)

你可以这样加入这两个表,然后在那之后添加你的where子句。

var query = from request in Requests 
            join requestLanguage in RequestLanguages 
            on request.LanguageId equals requestLanguage.LanguageId

答案 1 :(得分:1)

我认为这些简单的连接就是你所需要的

var query = from request in db.Requests
            join requestLanguage in db.RequestLanguages
              on request.requestId equals requestLanguage.requestId
            join userLanguage in db.UserLanguages
              on requestLanguage.languageId equals userLanguage.languageId
            where request.requestId == requestId && userLanguage.userId == userId
            select request;