LINQ查询从SQL转换,它使用包含GROUP BY和COUNT的子查询

时间:2013-10-19 10:17:05

标签: c# linq

首先,如果以前曾经问过这个问题,我会道歉但是我已经尝试在这里搜索了几十个问题(过了好几天)而我找不到合适的问题。

我正在尝试将常见的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

这需要生成一个List,其中包含具有多个职员的部门内的员工。

任何人都可以将此要求翻译成LINQ,Linq格式和使用方法(扩展名?)格式吗?

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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如何运作的更多信息,请参阅Jon Skeet的post on the topic