C# 一种计算列表中出现次数的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1139181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:09:38  来源:igfitidea点击:

A method to count occurrences in a list

c#.net-3.5listcountmatch

提问by Nona Urbiz

Is there a simple way to count the number of occurrences of all elements of a list into that same list in C#?

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

Something like this:

像这样的东西:

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

采纳答案by JP Alioto

How about something like this ...

这样的事情怎么样...

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

Edit per comment: I will try and do this justice. :)

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

In my example, it's a Func<int, TKey>because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

在我的示例中,这是Func<int, TKey>因为我的列表是整数。所以,我告诉 GroupBy 如何对我的项目进行分组。Func 接受一个 int 并返回我的分组的键。在这种情况下,我将得到一个IGrouping<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.
}

So, that's a Func that would take an int and return a string, just like ...

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

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

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

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

回答by Paul Sonier

Your outer loop is looping over all the words in the list. It's unnecessary and will cause you problems. Remove it and it should work properly.

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

回答by Stan R.

You can do something like this to count from a list of things.

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

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

To count a single element

计算单个元素

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();

回答by Steve Mitcham

var wordCount =
    from word in words
    group word by word into g
    select new { g.Key, Count = g.Count() };    

This is taken from one of the examples in the linqpad

这取自 linqpad 中的示例之一

回答by The Artist

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*
}