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

编程入门 行业动态 更新时间:2024-10-26 02:25:16
本文介绍了一种计算列表中出现次数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Is there a simple way to count the number of occurrences of all elements of a list into that same list in 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]); } }

推荐答案

这样的事情怎么样...

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. :)

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

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 ...

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

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

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

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.

更多推荐

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

本文发布于:2023-11-30 21:35:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651543.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:次数   方法   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!