建设项目数的词典列表中

编程入门 行业动态 更新时间:2024-10-23 06:17:53
本文介绍了建设项目数的词典列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含一串字符串,可以出现多次的List。我想借这个名单,并建立列表项为重点和它们的出现为价值的计数的字典

例如:

列表<串GT;东西=新的List<串GT;(); stuff.Add(花生酱); stuff.Add(大灌篮); stuff.Add(食品); stuff.Add(小吃); stuff.Add(哲学); stuff.Add(花生酱); stuff.Add(大灌篮); stuff.Add(食品);

和结果将是包含字典:

花生酱,2 大灌篮,2 民以食为天,2 小吃,1 哲学,1

我有办法做到这一点,但它似乎并不像我利用好东西用C#m的3.0

公众解释<字符串,整数> CountStuff(IList的<串GT; stuffList) {&字典LT;字符串,整数> stuffCount =新词典<字符串,整数>(); 的foreach(在stuffList串的东西){ //初始化或增加计数此项目如果(stuffCount.ContainsKey(东西)){ stuffCount [东东] ++; }其他{ stuffCount.Add(东东,1); } } 返回stuffCount; }

解决方案

您可以使用group子句。在C#中做到这一点。

列表<串GT;东西=新的List<串GT;(); ... 组VAR =从s的东西组由s s转换g选择 {新东西= g.Key,计数= g.Count()};

您可以调用扩展方法直接,以及如果你想:

VAR组= stuff.GroupBy(S = GT S)。选择(S =>新建{东西= s.Key,计数= S .Count之间的()});

从这里它是一个短的一跳将其放入一个词典<字符串, INT> :

VAR词典= groups.ToDictionary(G => g.Stuff,G = GT; g.Count);

I have a List containing a bunch of strings that can occur more than once. I would like to take this list and build a dictionary of the list items as the key and the count of their occurrences as the value.

Example:

List<string> stuff = new List<string>(); stuff.Add( "Peanut Butter" ); stuff.Add( "Jam" ); stuff.Add( "Food" ); stuff.Add( "Snacks" ); stuff.Add( "Philosophy" ); stuff.Add( "Peanut Butter" ); stuff.Add( "Jam" ); stuff.Add( "Food" );

and the result would be a Dictionary containing:

"Peanut Butter", 2 "Jam", 2 "Food", 2 "Snacks", 1 "Philosophy", 1

I have a way to do this, but it doesn't seem like I'm utilizing the good stuff in C# 3.0

public Dictionary<string, int> CountStuff( IList<string> stuffList ) { Dictionary<string, int> stuffCount = new Dictionary<string, int>(); foreach (string stuff in stuffList) { //initialize or increment the count for this item if (stuffCount.ContainsKey( stuff )) { stuffCount[stuff]++; } else { stuffCount.Add( stuff, 1 ); } } return stuffCount; }

解决方案

You can use the group clause in C# to do this.

List<string> stuff = new List<string>(); ... var groups = from s in stuff group s by s into g select new { Stuff = g.Key, Count = g.Count() };

You can call the extension methods directly as well if you want:

var groups = stuff.GroupBy(s => s).Select( s => new { Stuff = s.Key, Count = s.Count() });

From here it's a short hop to place it into a Dictionary<string, int>:

var dictionary = groups.ToDictionary(g => g.Stuff, g => g.Count);

更多推荐

建设项目数的词典列表中

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

发布评论

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

>www.elefans.com

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