【问题标题】:A method to count occurrences in a list一种计算列表中出现次数的方法
【发布时间】:2010-11-11 11:17:11
【问题描述】:

有没有一种简单的方法来计算列表中所有元素出现在 C# 中的同一列表中的次数?

类似这样的:

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;

string Occur;
List<string> Words = new List<string>();
List<string> Occurrences = new List<string>();

// ~170 elements added. . . 

for (int i = 0;i<Words.Count;i++){
    Words = Words.Distinct().ToList();
    for (int ii = 0;ii<Words.Count;ii++){Occur = new Regex(Words[ii]).Matches(Words[]).Count;}
         Occurrences.Add (Occur);
         Console.Write("{0} ({1}), ", Words[i], Occurrences[i]);
    }
}

【问题讨论】:

    标签: c# .net-3.5 list count match


    【解决方案1】:

    这样的事情怎么样...

    var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
    
    var g = l1.GroupBy( i => i );
    
    foreach( var grp in g )
    {
      Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
    }
    

    根据评论编辑:我会尽力做到这一点。 :)

    在我的示例中,它是 Func&lt;int, TKey&gt;,因为我的列表是整数。所以,我告诉 GroupBy 如何对我的项目进行分组。 Func 接受一个 int 并返回我分组的键。在这种情况下,我将得到一个IGrouping&lt;int,int&gt;(一组以 int 为键的 int)。例如,如果我将其更改为 (i =&gt; i.ToString()),我将通过字符串键入我的分组。您可以想象一个比按“1”、“2”、“3”键控更简单的例子……也许我制作了一个返回“一”、“二”、“三”作为我的键的函数……

    private string SampleMethod( int i )
    {
      // magically return "One" if i == 1, "Two" if i == 2, etc.
    }
    

    所以,这是一个接受 int 并返回字符串的 Func,就像 ...

    i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 
    

    但是,由于最初的问题要求知道原始列表值及其计数,所以我只是使用一个整数来键入我的整数分组以使我的示例更简单。

    【讨论】:

    • +1。计算每个不同元素的出现非常优雅。
    • FindAll 返回原始列表中与谓词匹配的元素列表,因此您必须为每个唯一元素执行一次才能找到该元素的计数。
    • 就用吧。很好的解决方案。如果要对其进行排序,只需使用:var g = l1.GroupBy( i =&gt; i ).OrderByDescending(group =&gt; group.Count());
    【解决方案2】:

    你可以做这样的事情来从列表中计数。

    IList<String> names = new List<string>() { "ToString", "Format" };
    IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);
    
    int count = methodNames.Where(x => names.Contains(x)).Count();
    

    计算单个元素

    string occur = "Test1";
    IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};
    
    int count = words.Where(x => x.Equals(occur)).Count();
    

    【讨论】:

    • +1:我花了一段时间才发现 GetMethods() 只是你的清单。 :)
    • 是的,我想到了这一点并决定让它更具可读性。谢谢,虽然我误读了这个问题。它说要计算“所有元素”..哎呀。这应该仍然足够有用。
    • @StanR。 - 这个解决方案适用于我的问题。但是,列表中是否有一种方法可以计算出大于或等于单词的出现次数?我使用的是“int”类型而不是“string”。
    • @MihirPatel 只需将 .Where 更改为 x > num || x == 数量
    【解决方案3】:
    var wordCount =
        from word in words
        group word by word into g
        select new { g.Key, Count = g.Count() };    
    

    这取自 linqpad 中的一个示例

    【讨论】:

      【解决方案4】:
      public void printsOccurences(List<String> words)
      {
          var selectQuery =
              from word in words
              group word by word into g
              select new {Word = g.Key, Count = g.Count()};
          foreach(var word in selectQuery)
              Console.WriteLine($"{word.Word}: {word.Count}");*emphasized text*
      }
      

      【讨论】:

        【解决方案5】:

        您的外部循环正在遍历列表中的所有单词。这是不必要的,会给你带来麻烦。删除它,它应该可以正常工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多