Haim Evgi
Haim Evgi

Reputation: 125476

c# associative array with dictionary

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 ,

first question :

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

and another question:

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 !

Upvotes: 0

Views: 4147

Answers (4)

Lee
Lee

Reputation: 144136

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

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.

Upvotes: 2

heijp06
heijp06

Reputation: 11788

To check if a key exists in a dictionary and use the value if it does, you can use TryGetValue:

ArrayList array;
if(!myDic.TryGetValue("blabla", out array))
{
    array = new ArrayList();
    myDic["blabla"] = array;
}
array.Add(42);

Upvotes: 1

Eric Lippert
Eric Lippert

Reputation: 660004

Use the right tool for the job. The data structure you want is called a "multi-dictionary" - that is a dictionary that maps from a key to a sequence of values, rather than from a key to a unique value.

The PowerCollections codebase contains an implementation of MultiDictionary that probably does what you want. I would use it rather than writing your own.

To sort the dictionary into a sequence of key/sequence pairs ordered by the length of the sequence, I would use a LINQ query with an "order by" clause. That seems like the easiest way to do it.

Upvotes: 5

Regan Sarwas
Regan Sarwas

Reputation: 453

Would something like this work:

        if (myDic.ContainsKey(myString))
            myDic[myString].Add(myNumber);
        else
            myDic.Add(myString, new ArrayList(new int[] {myNumber}));

Upvotes: 0

Related Questions