2

I am trying to get the count for the most common duplicate item in a list.

So far, I have:

List<string> brandList = new List<string>();

which contains 5 different soft drink brands, and the count is 100. I need to find out which brand has the most duplicates in the list and count how many duplicates there are.

AndrewRalon
  • 496
  • 1
  • 9
  • 24
chersharp
  • 37
  • 1
  • 7

6 Answers6

4

Presuming that your pseudo code actually was:

List<Brand> brandList=new List<Brand>();
// fill list

and your Brand class either overrides Equals+getHashCode or has a property like BrandID which is the identifier. N youow want to get the count of the most popular brand, you can use LINQ:

var mostPopularBrand = brandList.GroupBy(b => g.BrandID)
    .OrderByDescending(g => g.Count())
    .Select(g => new { BrandID = g.Key, Count =  g.Count()})
    .First();

Console.WriteLine("Most poular brand: {0} Count: {1}", 
                   mostPopularBrand.BrandID, mostPopularBrand.Count);

Update: If it's actually a List<string>(question was edited):

var mostPopularBrand = brandList.GroupBy(str => str)
    .OrderByDescending(g => g.Count())
    .Select(g => new { Brand = g.Key, Count =  g.Count()})
    .First();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

Your code doesn't compile. Providing that you mean List<String> as a storage of brands:

  var ListbrandList = new List<String>() {
    "Cola",
    "Juice",
    "Cola",
    "Water",
    "Milk",
    "Water",
    "Cola",
  };

  var result = ListbrandList
    .GroupBy(item => item)
    .Select(item => new {
         Name = item.Key,
         Count = item.Count()
       })
    .OrderByDescending(item => item.Count)
    .ThenBy(item => item.Name);

  String report = String.Join(Environment.NewLine, result
    .Select(item => String.Format("{0} appears {1} time(s)", item.Name, item.Count)));

you'll have report as

  Cola appears 3 time(s)
  Water appears 2 time(s)
  Juice appears 1 time(s)
  Milk appears 1 time(s)      
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1
var result = brandList
            .Distinct()
            .GroupJoin(brand,
            k => k,
            b => b,
            (k, b) => new { BrandName = k, Count = b.Count() });

// An usage could be...

foreach (var r in result)
{
    Debug.WriteLine("{0} Brand has {1}", r.BrandName, r.Count);
}

Without LinQ:

var result = new Dictionary<string, int>();

foreach (var brand in brandList)
{
    if (!result.ContainsKey(brand))
    {
        var count = brandList.FindAll(x => x.Equals(brand)).Count;
        result.Add(brand, count);
    }
}

foreach (var r in result)
{
    Console.WriteLine("{0} Brand has {1}", r.Key, r.Value);
}
MMZurita
  • 125
  • 8
0

Something like this maybe:

var res = brandList.GroupyBy(x => x)
    .Select(x => new {Key = x.Key, Count = x.Count});

Now you have a list containing the actual drink-number and the count for this number.

EDIT: Getting the brand with most count is now easy, e.g. by using:

var mostPopular = res.Single(x => x.Count == res.Max(y => y.Count)); 

EDIT2: Without LINQ the following might work, which is way longer and more complicated:

// get the count for every brand

Dictionary<string, int> res = new Dictionary<string, int>();
foreach(var x in brands)
{
    if (!res.ContainsKey(x)) res[x] = 0;
    res[x]++;
}

// now get the max count

int currentMax = 0;
string key = "";
foreach (var kv in res)
{
    if (kv.Value > currentMax)
    {
        currentMax = kv.Value;
        key = kv.Key;
    }
}

Now the key should contain the brand with highest Count.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
0

You can try to do group using LINQ by Elements and calculate count

var groupedList = from l in ListbrandList
    group l by l into grp
    select new { key = grp.Key, cnt = grp.Count()};

Then you will have group by key (Element) and value (Count)

Andrii Tsok
  • 1,386
  • 1
  • 13
  • 26
0

To count element with specific value in a list use :

int quantity = lst.Count(r => r == "Cola");

Example :

List<string> lst = new List<string>()
{
    "Sprite",
    "Cola",
    "Sprite",
    "Sprite",
    "Cola",
    "Sprite",
    "Sprite",
    "Cola",
    "Pepsi",
    "Sprite",
    "Pepsi",
    "Sprite",

};

string[] popularBrands = { "Cola", "Pepsi" };

int[] quantities = new int[popularBrands.Length];

for (int i = 0; i < popularBrands.Length; i++)
{
    quantities[i] = lst.Count(r => r.ToUpper() == popularBrands[i].ToUpper());
    Console.WriteLine("{0}  :   {1}", popularBrands[i], quantities[i]); 
}

Output

Cola : 3
Pepsi : 2

P.S.

About this code r => r.ToUpper() == popularBrands[i].ToUpper() : r is variable that holds a value from our list (that are taken one by one). We also use ToUpper() to make sure that our check is case insensitive.

So we basically loop through the collection taking values out of it one by one. Each time we put value to r variable and check if this variable satisfies condition. If so - we count it, if not - we just move to next value.

Tshilidzi Mudau
  • 7,373
  • 6
  • 36
  • 49
Fabjan
  • 13,506
  • 4
  • 25
  • 52