我是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
答案 0 :(得分:2)
嗨,得到你想要的东西应该不难。
tablename.GroupBy(g => g.dept)
.Select(s => new {
dept = s.Key,
sal = s.Sum(t => t.sal)
})
.ToList();
这会为您提供每个部门的总薪资清单
答案 1 :(得分:0)
类似的东西:
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()
调用到您的dataTable。
另请查看Here
答案 2 :(得分:0)
你可以做这样的事情......
var list = table.GroupBy(p=>p.dept,q=>q.sal).Select(x=>new { dept = x.Key, sal = x.Sum(s=>s.sal)});
答案 3 :(得分:-1)
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();