在这里我的查询是我有一个重复数据的列表,对此,我想在groupby
列上执行FName
子句,并通过递减计数顺序显示并显示该记录的所有记录特定列表
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { ID = 1, FName = "John", Age = 23, Sex = 'M' });
empList.Add(new Employee() { ID = 2, FName = "Mary", Age = 25, Sex = 'F' });
empList.Add(new Employee() { ID = 3, FName = "John", Age = 28, Sex = 'M' });
empList.Add(new Employee() { ID = 4, FName = "Amber", Age = 23, Sex = 'M' });
empList.Add(new Employee() { ID = 5, FName = "Kathy", Age = 25, Sex = 'M' });
empList.Add(new Employee() { ID = 6, FName = "Lena", Age = 27, Sex = 'F' });
empList.Add(new Employee() { ID = 7, FName = "John", Age = 28, Sex = 'M' });
empList.Add(new Employee() { ID = 8, FName = "Kathy", Age = 27, Sex = 'F' });
var dup1 = empList
.GroupBy(x => new { x.FName })
.Select(group => new { Name = group.Key.FName, Count = group.Count() })
.OrderByDescending(x => x.Count);
foreach (var x in dup1)
{
Console.WriteLine(x.Count + " " + x.Name);
}
从上面的代码中,我得到这样的输出:
但是我真正想要的是这样的:
答案 0 :(得分:1)
您似乎希望组计数,然后是有关组中第一项的信息。如果是这种情况,那么您可以简单地使用GroupBy
对项目进行分组,然后在输出中捕获并显示该组中第一个项目的信息:
var groups = empList.GroupBy(e => e.FName).OrderByDescending(group => group.Count());
foreach (var group in groups)
{
var first = group.First();
Console.WriteLine($"{group.Count()} {first.FName}\t{first.Age} {first.Sex}");
}
输出
答案 1 :(得分:0)
.Select(group => new
{
Name = group.Key.FName,
Count = group.Count(),
Age = group.First().Age,
Sex = group.First().Gender
});