C#关联数组字典 [英] c# associative array with dictionary

查看:214
本文介绍了C#关联数组字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个Dictonary是这样的:

I want to build an Dictonary like this :

Dictionary<String, ArrayList> myDic = new Dictionary<String, ArrayList>();



在最后,我要像一个结构:

in the end i want a structure like :

["blabla"] => array(1,2,3)
["foo"] => array(1,4,6,8) 
.......



建立这个我在一个循环中运行,并在每个循环建立一些字符串,

to build this i run in a loop and in every loop build some strings ,

第一个问题:

如何检查每次如果此字符串存在于词典
,如果它不存在,打开字典,一个元素的数组列表的新条目,如果只存在另一个元素添加到数组名单

how to check every time if this string exists in the dictionary , if its not exists open a new entry in dictionary with one element in the array list, if exists only add another element to the array list

而另一个问题

我如何可以根据排序,这本字典在数组列表元素(降序)像数:

how can i sort this dictionary according to number of elements in the array list(In descending order) like :

["foo"] => array(1,4,6,2,8)     
["bar"] => array(4,6,2,8) 
["bla"] => array(1,2,3)
["blo"] => array(1,2)    
    .......



谢谢!

thanks !

推荐答案

而不是的ArrayList 你应该使用数组或列表< T> 。假设你有一个词典<字符串,整数> 称为源这应该工作:

Instead of ArrayList you should use an array or List<T>. Assuming you have a Dictionary<string, int> called source this should work:

var items = source
    .GroupBy(kvp => kvp.Key)
    .Select(grp => new { Key = grp.Key, Items = grp.Select(kvp => kvp.Value).ToArray() })
    .OrderByDescending(i => i.Items.Length);

要解释,词典< TKEY的,TValue> 工具的IEnumerable< KeyValuePair< TKEY的,TValue>> 这样也算是键 - 值对的序列。由集团集团对通过键,然后选择创建分别包含一个密钥和项目属性键和关联值匿名类型的序列。这个序列,然后通过在产品项目的数量排序阵列中的每个对象。

To explain, Dictionary<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>> so can be considered a sequence of key-value pairs. Group by groups the pairs by key and then Select creates a sequence of an anonymous type which contains the key and associated values in a Key and Items property respectively. This sequence is then ordered by the number of items in the Items array of each object.

如果你想通过创建数组的长度命令他们,你不能使用字典,因为它们没有排序。

If you want to order them by the length of the created array, you can't use a dictionary since they are not ordered.

这篇关于C#关联数组字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆