sang
sang

Reputation: 29

Lambda expression groupby on single column and fetch all column orderby count

Here my query is I have a list with repeated data and on that, I want to do groupby clause on FName column and display in order by descending of a count and display all record of that particular list

        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);
        }

From the above code I am getting output like this:

enter image description here

But what i actually want is like this:

enter image description here

Upvotes: 0

Views: 727

Answers (2)

Rufus L
Rufus L

Reputation: 37020

It looks like you want the group count, and then the information about the first item in the group. If that's the case, then you can simply use GroupBy to group the items, and then in your output just capture and display the information for the first item in the group:

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}");
}

Output

enter image description here

Upvotes: 1

Without Haste
Without Haste

Reputation: 642

.Select(group => new
{
    Name = group.Key.FName, 
    Count = group.Count(),
    Age = group.First().Age,
    Sex = group.First().Gender
});

Upvotes: 0

Related Questions