我想知道列表中每个项目的计数

时间:2015-08-26 13:12:24

标签: c# list count

所以,我有一张投票清单。

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

最多有三个不同的字符串。我想得到他们的数量。这是在c#。

我已经查看了之前的问题,但没有找到类似的东西,没有问题比我的更复杂。 对不起,如果已经回答

4 个答案:

答案 0 :(得分:5)

呃, Linq 是这样的?:

  List<String> votes = new List<String>() {
    "Yes", "No", "Yes", "No", "?"
  };
  ...
  String report = String.Join(Environment.NewLine, votes
    .GroupBy(item => item)
    .Select(chunk => String.Format("{0} votes, count {1}", chunk.Key, chunk.Count())) 
  );

  Console.Write(report); 

答案 1 :(得分:3)

您可以使用GroupBy

var voteGroups = Votes.GroupBy(s => s);

现在,如果您想知道每个string使用Enumerable.Count的计数:

foreach(var voteGroup in voteGroups)
    Console.WriteLine("Vote:{0} Count:{1}", voteGroup.Key, voteGroup.Count());

另一种方法是使用ToLookup

var voteLookup = Votes.ToLookup(s => s);
foreach (var voteGroup in voteLookup)
    Console.WriteLine("Vote:{0} Count:{1}", voteGroup.Key, voteGroup.Count());

查找具有它的优点,它使您能够找到像字典这样的特定元素。所以你可以用这种方式获得&#34; pepsi&#34; -count:

int pepsiCount = voteLookup["Pepsi"].Count();

如果列表中没有这样的字符串,则不会导致异常(count将为0)。

如果你想让它不区分大小写,那就治疗&#34; pepsi&#34;和&#34;百事可乐&#34;平等:

var voteLookup = Votes.ToLookup(s => s, StringComparer.InvariantCultureIgnoreCase);

答案 2 :(得分:0)

不是最好的代码,但它有效:

int count1 = 0;
int count2 = 0;
foreach (String answer in Votes)
{
  if (answer == "yes")
  {
    count1++;
  }
  if (answer == "no")
  {
    count2++;
  }
}

答案 3 :(得分:-2)

如果你拥有List strings,那么你可以使用Count属性。

List<string> Votes = new List<string>();
// populate list here
Console.WriteLine(Votes.Count);