简体   繁体   中英

How to convert this SQL statement to Linq for C#

I am trying to convert my simple SQL statement into Linq format for my C# application but I always seem to struggle making the conversion. I downloaded linqpad and have been playing around with it but I'm still having issues with the proper format.

My SQL statement:

SELECT distinct PictureCity, PictureState
FROM Website_Gallery
GROUP BY PictureCity, PictureState, PictureDate
ORDER BY PictureCity, PictureState

The results are ordered by PictureCity and look like this:

Abington    MA
Acton   MA
Acushnet    MA
Agawam  MA
Andover MA
Arlington   MA
Arlington   TX
Ashby   MA
Ashland MA

What I have so far in my C# application which I can't seem to get to work. (I suck at linq).

var Results = _context.Website_Gallery
.(g => g.PictureCity, g => g.PictureState).AsEnumerable()
.Select g
.GroupBy(g => g)

Seems like all you need is

var results = _context.Website_Gallery
    .OrderBy(x => x.PictureCity)
    .ThenBy(x => x.PictureState)
    .Select(x => new { x.PictureCity, x.PictureState })
    .Distinct();

that would be equivalent to the following SQL

SELECT distinct PictureCity, PictureState
FROM Website_Gallery
ORDER BY PictureCity, PictureState

because what you had did not need the group by

Note you can then either iterate that result in a foreach or tack a ToList to the end to materialize the query into memory.

SQL

SELECT distinct PictureCity, PictureState
FROM Website_Gallery
ORDER BY PictureCity, PictureState

Linq

var Results = _context.Website_Gallery
                  .Select(g => new { g.PictureCity, g.PictureState })
                  .Orderby(p => p.PictureCity).ThenBy(p => p.PictureState)
                  .Distinct().ToList();

Or you can also do this

var Results = _context.Website_Gallery
            .GroupBy(x => new { PictureCity = x.PictureCity, PictureState = x.PictureState })
            .Select(g => new { g.Key.PictureCity, g.Key.PictureState }).Orderby(p => p.PictureCity).ThenBy(p => p.PictureState)
            .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM