简体   繁体   中英

SQL query to LINQ(lambda)

I'm new to linq, so not to sure of the context but what i need is to convert the following sql statement into linq( lambda), to return a list of data.

SELECT 
    SUM(Total) AS Total, SHIFT, SHIFT_LETTER
FROM 
    [Table]
WHERE 
    SHIFT_DAY >= '2015-06-28' AND 
    SHIFT_DAY <= '2015-06-29' AND 
    MACHINE = 'Machine'
GROUP BY 
    SHIFT, SHIFT_LETTER

Your query is straight-forward:-

var result = from x in db.Table
             where x.shift_DAY >= "2015-06-28"
                   && x.shift_DAY <= "2015-06-29" && x.MACHINE == "Machine"
             group x by new { x.SHIFT, x.SHIFT_LETTER } into g
             select new 
             {
                Total = g.Sum(z => z.Total),
                SHIFT = g.Key.SHIFT,
                SHIFT_LETTER = g.Key.SHIFT_LETTER
             };

With Lambda:-

var result = db.Table.Where(x => x.shift_DAY >= "2015-06-28" 
                                 && x.shift_DAY <= "2015-06-29" 
                                 && x.MACHINE == "Machine")
              .GroupBy(x => new { x.SHIFT, x.SHIFT_LETTER })
              .Select(x => new 
                         {
                              Total = x.Sum(z => z.Total),
                              SHIFT = x.Key.SHIFT,
                              SHIFT_LETTER = x.Key.SHIFT_LETTER
                         });

Please note you need to convert the dates accordingly.

If you are using Linq to Entities , you can do this:

DateTime dt1 =DateTime.ParseExact("2015-06-28", "yyyy-MM-dd",System.Globalization.CultureInfo.InvariantCulture); 

DateTime dt2 =  DateTime.ParseExact("2015-06-29", "yyyy-MM-dd",System.Globalization.CultureInfo.InvariantCulture); 

var query= from e in context.Table
           where e.ShiftDay>=dt1 && e.ShiftDay<= dt2 && e.Machine=="Machine"
           group e by new{ e.Shift, e.ShiftLetter} into g
           select new{ Total= g.Sum(e=>e.Total), Shift=g.Key.Shift, ShiftLetter=g.Key.ShiftLetter};

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