-1

I have a class with constructor and some properties set to it. I need to find most commonly repeating property and count of it.

class Car
{
    public string Make { get; set; }

    public Car(string make)
    {
        this.Make = make;
    }
}

I've created a list called "cars" with 7 members and set these car makes: Audi, Volvo, Volvo, BMW, Audi, Audi, Audi (most common being Audi).

How can I find and output the most common "Make" and count of it?

1 Answers1

1

You can use this:

using System.Linq;
using System.Collections.Generic;

void TestCar()
{
  var list = new List<Car>();

  list.Add(new Car("Audi"));
  list.Add(new Car("Volvo"));
  list.Add(new Car("Audi"));
  list.Add(new Car("BMW"));
  list.Add(new Car("Audi"));

  var query = ( from car in list
                group car by car.Make into cars
                select new { Key = cars.Key, Count = cars.Count() } );

  var result = query.OrderByDescending(item => item.Count).FirstOrDefault();

  if (result != null) 
    MessageBox.Show(result.Key + " count = " + result.Count);
}
  • I need to find most common make (in most cases it will not be "Audi", I put it as an example). – Gytis Dokšas Sep 07 '19 at 20:31
  • Indeed, the answer had been updated. –  Sep 07 '19 at 20:38
  • It works but I don't understand how it does sadly – Gytis Dokšas Sep 07 '19 at 20:44
  • The linq statement count every "Make" grouped by this property as we count every occurences. Next we order by descending on the count column. Result here is "Audi|3,Volvo|1,BMW|1". So we take the first row where Key = "Audi" and Count = 3. The order may be put in the linq statement. https://learn.microsoft.com/dotnet/csharp/linq/group-query-results –  Sep 07 '19 at 21:01
  • You should consider that there may be several most Make with same Count. You can take the FirstOrDefault on the result and get the Count value as countMax. Next you can use on the same result TakeWhile(key => key == countMax) and do a foreach to display most make cars. –  Sep 07 '19 at 21:16