Showing posts with label dictionary. Show all posts
Showing posts with label dictionary. Show all posts

Wednesday, 30 November 2011

c# how to dispose objects of Dictionary

 
problem

c# dispose objects of Dictionary
you cannot dispose the object of a Dictionary with "foreach" process, you can do with "while" getting the Enumerator of the Dictionary.
difficulty level

5/10 :|
compatibility

c#
solution

In the follow example, I scan serially a Dictionary generic of <string, IInDataObject> type and I dispose its hosted objects.
Each object in the dictionary, each Value is IInDataObject interface. This interface implements IDisposable so can call Dispose();

//get the Enumerator in order to scan with while (and not with foreach)
System.Collections.IEnumerator enumerator = dataObjectList.GetEnumerator();
//perform the Enumerator in while loop
while (enumerator.MoveNext()) {
    //get the pair of Dictionary
    KeyValuePair<string, IInDataObject> pair =
        ((KeyValuePair<string, IInDataObject>)(enumerator.Current)); 
    //dispose it
    pair.Value.Dispose();
       
}

Tuesday, 29 November 2011

csharp, process the items of Dictionary serial and faster

The Dictionary type abstracts out its looping logic into enumerators: these are accessed through the foreach loop and the GetEnumerator method. In this article, we demonstrate the GetEnumerator method, which exhibits better performance than the foreach loop.

Examples

Let's examine the most common and easiest way to loop through a Dictionary instance. The foreach loop here actually compiles into intermediate language that uses the GetEnumerator method, MoveNext, and Current, as well as a try/finally block.
Finally
Looping over Dictionary with foreach [C#]

static int A(Dictionary<string, int> d)
{
    int a = 0;
    foreach (var pair in d)
    {
 a += pair.Value;
    }
    return a;
}
Next, this method demonstrates the GetEnumerator and MoveNext methods and the Current property directly. This code is compiled to the same intermediate language except the try/finally block is absent.
Looping over Dictionary with GetEnumerator [C#]

static int B(Dictionary<string, int> d)
{
    int b = 0;
    var enumerator = d.GetEnumerator();
    while (enumerator.MoveNext())
    {
 var pair = enumerator.Current;
 b += pair.Value;
    }
    return b;
}