Distinct list from List with Count

BigH61 581 Reputation points
2023-04-22T22:50:18.56+00:00

I have a List<Object> and object has many fields one of these is LastName. How would i get a list of distinct LastNames and a Count of each time that LastName occured. For Example Jones, Smith, Anderson, Colins, Smith, Jones Would return list Jones, 2 Smith, 2 Anderson, 1 Colins, 1 Update I have managed to achieve the below but in stead of var results I would like a List of Object type Name, Count. Is this possible?

var results = mylist.GroupBy(n=>n.LastName).Select(g=> new{ Name = g.First().LastName, Count = g.Count()}).ToList();

Thank you for your assistance.

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2023-04-23T09:55:34.92+00:00

    Try this:

    class MyObject
    {
       public string Name { get; set; }
       public int Count { get; set; }
    }
    
    . . . .
    
    List<MyObject> results = mylist.GroupBy( n => n.LastName ).Select( g => new MyObject { Name = g.Key, Count = g.Count( ) } ).ToList( );
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.