我是Asp .Net
中linq
查询的新手。我想要按概念分组的部门总工资。我想要使用linq
查询的结果,所以请帮助我的朋友。我拿了一张表格,见下文。你能为我的查询提供一个解决方案吗?我试过了,但没有找到解决方案。
我的数据表是:
id name dept sal
1 ABC it 10000
2 BBC it 20000
3 CCA hr 30000
4 DDA hr 40000
5 MMN admin 50000
结果像:
dept sal
-----------------
It 30000
Hr 70000
Admin 50000
嗨,
得到你想要的东西应该不难。
tablename.GroupBy(g => g.dept)
.Select(s => new {
dept = s.Key,
sal = s.Sum(t => t.sal)
})
.ToList();
这为您提供了每个部门的总工资列表
你可以做这样的事情..
var list = table.GroupBy(p=>p.dept,q=>q.sal).Select(x=>new { dept = x.Key, sal = x.Sum(s=>s.sal)});
有人这样想:
context.table.GroupBy(t => t.dept, e => e.sal).Select(r => new { key = r.Key, sum = r.Sum(x => x) });
编辑:
要将 linq 与 dataTable 一起使用,请添加对 System.Data.DataSetExtensions
的引用,并添加System.Data
命名空间并将AsEnumerable()
调用到数据表。也看看这里
List<Student> studentsList = new List<Student>()
{
new Student(){Id = 1,Name ="krish",Gender="male",City="ahmedabad",Salary=2750},
new Student(){Id = 2,Name ="rahul",Gender="male",City="delhi",Salary=1000},
new Student(){Id = 3,Name ="neha",Gender="female",City="surat",Salary=2500},
new Student(){Id = 4,Name ="dev",Gender="male",City="mumbai",Salary=7800},
new Student(){Id = 5,Name ="priya",Gender="female",City="ahmedabad",Salary=5600},
};
var queryList = from SL in studentsList group SL by SL.Gender into GROUPGENDER orderby GROUPGENDER.Key select GROUPGENDER;
foreach(var studentList in queryList)
{
Console.WriteLine(">>>>>group by<<<<<");
Console.WriteLine(studentList.Key);
Console.WriteLine(">>>>>group by<<<<<");
foreach (var item in studentList)
{
Console.WriteLine(item.Id);
Console.WriteLine(item.Name);
Console.WriteLine(item.Gender);
Console.WriteLine(item.City);
}
}
Console.Read();