61

有没有一种简单的方法可以将列表中所有元素的出现次数计算到 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]);
    }
}
4

6 回答 6

110

像这样的东西怎么样...

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

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

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

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

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

于 2009-07-16T17:51:33.807 回答
22

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

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();
于 2009-07-16T17:49:38.177 回答
15
var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

这取自 linqpad 中的示例之一

于 2009-07-16T17:55:54.793 回答
2
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*
}
于 2020-05-17T10:53:51.817 回答
0

这是一个避免使用 Linq 但只使用更多代码的版本。

// using System.Collections.Generic;

Dictionary<int, int> oGroups = new Dictionary<int, int>();
List<int> oList = new List<int>() { 1, 2, 3, 4, 5, 2, 2, 2, 4, 4, 4, 1 };

foreach (int iCurrentValue in oList)
{
    if (oGroups.ContainsKey(iCurrentValue))
        oGroups[iCurrentValue]++;
    else
        oGroups.Add(iCurrentValue, 1);
}

foreach (KeyValuePair<int, int> oGroup in oGroups)
{
    Console.WriteLine($"Value {oGroup.Key} appears {oGroup.Value} times.");
}
于 2022-02-15T20:50:38.640 回答
-4

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

于 2009-07-16T17:48:25.747 回答