2009-12-12 77 views
0

如何以下SQL轉換爲LINQSQL到LINQ等效

select sum(salary),Deptid from person where deptid=1 or deptid=2 group by 
deptid 
+0

發生了什麼事到你的第二個問題?它被刪除了......是你刪除了它嗎? –

+0

我問,因爲我即將發佈的答案,然後StackOverflow告訴我,我不能,因爲它已被刪除。 –

+0

對不起,我刪除了它 – user215675

回答

3
 var salaries = persons 
      .Where(p => p.DeptId == 1 || p.DeptId == 2) 
      .GroupBy(p => p.DeptId) 
      .Select(x => new { DeptId = x.Key, TotalSalary = x.Sum(p => p.Salary)}); 

這裏有一個完整的例子:

using System; 
using System.Collections.Generic; 
using System.Linq; 

class Program 
{ 
    class Person 
    { 
     public int DeptId { get; set; } 
     public int Salary { get; set; } 
    } 

    static void Main(string[] args) 
    { 
     List<Person> persons = new List<Person>(); 
     persons.Add(new Person { DeptId = 1, Salary = 10000 }); 
     persons.Add(new Person { DeptId = 1, Salary = 20000 }); 
     persons.Add(new Person { DeptId = 1, Salary = 30000 }); 
     persons.Add(new Person { DeptId = 2, Salary = 40000 }); 
     persons.Add(new Person { DeptId = 3, Salary = 50000 }); 

     var salaries = persons 
      .Where(p => p.DeptId == 1 || p.DeptId == 2) 
      .GroupBy(p => p.DeptId) 
      .Select(x => new { DeptId = x.Key, TotalSalary = x.Sum(p => p.Salary)}); 

     foreach (var dept in salaries) 
      Console.WriteLine("{0}: {1}", dept.DeptId, dept.TotalSalary); 
    } 
} 

輸出:

1: 60000 
2: 40000 
3
var qry = from p in dc.Persons 
where p.deptid==1 || p.deptid==2 
group p by p.deptid into g 
select new { Total = g.Sum(q=>q.salary), DeptId=g.Key }; 
+0

小心:裸頭回答:-) –

+0

+1有幫助的回覆 – user215675