获取列表中重复项的计数

时间:2015-07-16 08:59:23

标签: c# winforms list count duplicates

我正在尝试获取列表中最常见的重复项目的计数。

到目前为止,我有:

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

包含5个不同的软饮料品牌,计数为100。我需要找出哪个品牌在列表中具有最多重复项,并计算有多少重复项。

6 个答案:

答案 0 :(得分:3)

假设您的伪代码实际上是:

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

并且您的Brand课程会覆盖Equals + getHashCode,或者拥有BrandID这样的属性作为标识符。 N youow想得到最受欢迎品牌的数量,你可以使用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);

更新:如果它实际上是List<string>(问题已被修改):

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

答案 1 :(得分:3)

您的代码d 无法编译。假设您将List<String>视为品牌存储:

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

你将report作为

  Cola appears 3 time(s)
  Water appears 2 time(s)
  Juice appears 1 time(s)
  Milk appears 1 time(s)      

答案 2 :(得分:0)

这样的事情可能是:

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

现在您有一个列表,其中包含实际饮品编号和此编号的计数。

编辑:获得最多计数的品牌现在很容易,例如使用:

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

EDIT2:如果没有LINQ,以下内容可能会起作用,这会更长,更复杂:

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

现在key应该包含品牌Count

答案 3 :(得分:0)

您可以尝试使用LINQ by Elements进行分组并计算计数

topdown

然后您将按键分组(元素)和值(计数)

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

要计算列表中具有特定值的元素,请使用:

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

示例:

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

输出

Cola : 3
Pepsi : 2

P.S。

关于此代码r => r.ToUpper() == popularBrands[i].ToUpper(): r是变量,它保存我们列表中的值(逐个获取)。我们还使用ToUpper()来确保我们的检查不区分大小写。

所以我们基本上循环遍历集合,逐个取值。每次我们将值放到r变量并检查此变量是否满足条件。如果是这样 - 我们会计算它,如果不是 - 我们只是转到下一个值。