2013-10-19 51 views
2

首先,如果之前已經詢問過此問題,但我已嘗試通過此處(幾天)搜索幾十個問題並且找不到合適的問題表示歉意。LINQ查詢從使用包含GROUP BY和COUNT的子查詢的SQL進行轉換

我想將常見的SQL查詢翻譯成LINQ。下面是一個簡單的代碼版本,如果我能夠使用SQL語句...

List<T> myData = new List<T>(); // (Employee, Age, Department); 
myData.Add("Bill", 34, "IT"); 
myData.Add("Fred", 23, "ACCOUNTS"); 
myData.Add("Jane", 44, "SALES"); 
myData.Add("Sally", 56, "IT"); 
myData.Add("Harry", 33, "ACCOUNTS"); 


List<T> filteredData = SELECT * FROM myData 
           WHERE Department IN (
           SELECT Department 
           FROM myData 
           GROUP BY Department 
           HAVING (COUNT(Department) > 1) 
           ) 
         ORDER BY Department, Employee 

So that filteredData contains: 
          Fred, 23, ACCOUNTS 
          Harry, 33, ACCOUNTS 
          Bill, 34, IT 
          Sally, 56, IT 

這需要產生包含有一個以上的工作人員部門內工作人員名單。

任何人都可以將這個需求轉換成LINQ,Linq格式和使用方法(擴展名?)格式嗎?

回答

2

這應該工作太:

var filteredData = myData.GroupBy(x => x.Department) 
         .Where(x => x.Count() > 1) 
         .SelectMany(x => x) 
         .OrderBy(x => x.Department) 
         .ThenBy(x => x.Employee) 
         .ToList(); 
+0

非常簡單,很好的答案 – VahiD

+0

是的,但又是ORDER BY? – gaw

+0

@gaw我錯過了,我會添加它。 – nawfal

1

這裏是抽象數據類:

public class Emp 
     { 
      public string Employee { get; set; } 
      public string Age { get; set; } 
      public string Department { get; set; } 
     } 

,這是通過做組所需的LINQ:

private void button1_Click(object sender, EventArgs e) 
      { 

     List<Emp> myData = new List<Emp>(); // (Employee, Age, Department); 
        myData.Add(new Emp{Employee = "Bill",Age ="34",Department = "IT"}); 
        myData.Add(new Emp { Employee = "Fred", Age = "23", Department = "ACCOUNTS" }); 
        myData.Add(new Emp { Employee = "Jane", Age = "44", Department = "SALES" }); 
        myData.Add(new Emp { Employee = "Sally", Age = "56", Department = "IT" }); 
        myData.Add(new Emp { Employee = "Harry", Age = "33", Department = "ACCOUNTS" }); 

        var results = from p in myData 
         group p by p.Department into g 
         select new { Department = g.Key, Result = g.Count() }; 

        var filteredData = myData.Where(x => results.Where(y => y.Result > 1).Select(z=> z.Department).Contains(x.Department)).OrderBy(em=> em.Department).ThenBy(em2=> em2.Employee).ToList(); 
    } 

更多關於的GroupBy是如何工作的,請參閱喬恩斯基特的post on the topic

+0

您在使用System.Linq的補充;並使用system.Collections.Generic; – VahiD

+1

謝謝@VahiD。這似乎工作正常,除了我需要filteredData是一個列表,所以我改變var filteredData到列表 filteredData並添加.ToLIst()在最後。對於其他用途,你可以編輯你的答案來顯示這些?另外,它不是ORDER BY Department,Employee? – gaw

+0

是的,這是正確的,我也可以添加這些也 – VahiD