【问题标题】:Convert from SQL to LINQ in c# (.Net) [duplicate]在c#(.Net)中从SQL转换为LINQ [重复]
【发布时间】:2017-10-28 18:38:43
【问题描述】:

我想将它从 SQL 转换为 Linq,但我不知道确切的语法:

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

【问题讨论】:

  • 我尝试的所有东西都脱离了上下文我无法掌握 linq 语法,这应该返回到列表中,但我不知道我只知道如何编写这个 insql
  • 你在使用实体框架吗?
  • 是的,我正在使用实体框架
  • 一个人如何从转换工具中学习?这不是一个重复的问题。搁置是没有效率的。

标签: c# sql asp.net .net linq


【解决方案1】:

尝试关注

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

【讨论】:

    【解决方案2】:

    你可以试试这个。

    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  
                }
    

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 2012-07-04
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多