2017-10-28 76 views
-1

我想這個從SQL到LINQ轉換,但我不知道確切的語法:從SQL轉換爲LINQ在C#(.NET)

SELECT TOP 1 
    R.GalleryId a, COUNT(*) b, G.Address ad 
FROM 
    [PiArt].[dbo].[Rents] R, [PiArt].[dbo].[Galleries] G 
WHERE 
    R.GalleryId = G.GalleryId 
GROUP BY 
    R.GalleryId, G.Address 
ORDER BY 
    COUNT(*) DESC 
+3

你到目前爲止試過了什麼? – MadOX

+0

我嘗試過的所有東西都是出於上下文我不能grap的linq語法這應該返回到列表,但我不知道我是如何知道如何寫這個insql –

+0

你使用實體框架? –

回答

0

嘗試以下

class Program 
    { 
     static void Main(string[] args) 
     { 
      List<Gallery> galleries = new List<Gallery>(); 
      List<Rent> rents = new List<Rent>(); 


      var results = (from r in rents 
          join g in galleries on r.GallerId equals g.GallerId 
          select new { r = r, g = g }) 
          .GroupBy(x => new { id = x.r.GallerId, address = x.r.Address }) 
          .Select(x => new { 
           count = x.Count(), 
           id = x.Key.id, 
           address = x.Key.address 
          }) 
          .OrderByDescending(x => x.count) 
          .FirstOrDefault(); 
     } 
    } 

    public class Gallery 
    { 
     public int GallerId { get; set; } 
    } 
    public class Rent 
    { 
     public int GallerId { get; set; } 
     public string Address { get; set; } 
    } 
0

你可以試試這個。

from R in Rents 
join G in Galleries on R.GalleryId equals G.GalleryId 
group new {R,G} by new { R.GalleryId , G.Address} into GRP 
orderby GRP.Count() descending 
select new { 
       a= GRP.Key.GalleryId, 
       b = GRP.Count(), 
       ad = GRP.Key.Address 
      }