블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2106)
Unity3D (470)
Programming (453)
Unreal (2)
Gamebryo (56)
Tip & Tech (162)
협업 (26)
3DS Max (3)
Game (12)
Utility (101)
Etc (88)
Link (29)
Portfolio (18)
Subject (90)
iPhone (30)
Android (2)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (1)
Memories (16)
Interest (36)
Thinking (34)
한글 (23)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (16)
Exercise (3)
나만의 맛집 (2)
냥이 (7)
육아 (2)
Total1,099,602
Today111
Yesterday326
Statistics Graph

달력

« » 2017.10
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        

공지사항

태그목록

Tistory Cumulus Flash tag cloud by BLUEnLIVE requires Flash Player 9 or better.

Code (CSharp):
  1. var enumerator = my_dictionary.GetEnumerator();
  2. while( enumerator.MoveNext() )
  3. {
  4.     // Access value with enumerator.Current.Value;
  5. }



[출처] https://forum.unity3d.com/threads/c-dictionary-loop.337804/

저작자 표시 비영리 동일 조건 변경 허락
신고

'Programming > C#' 카테고리의 다른 글

[펌] string을 byte[] 배열로 변환?  (0) 2017.01.10
[펌] 반복문 유틸  (0) 2016.12.07
[펌] Loop Dictionary  (0) 2016.12.07
[펌] String -> enum 변환  (0) 2016.05.23
[펌] C# - 정규식을 이용한 문자 변환  (0) 2016.04.15
[C#] 시간체크(Stopwatch)  (0) 2015.09.15
Posted by blueasa

댓글을 달아 주세요

public static class Extensions
{
    public static bool TryGetKey<K, V>(this IDictionary<K, V> instance, V value, out K key)
    {
        foreach (var entry in instance)
        {
            if (!entry.Value.Equals(value))
            {
                continue;
            }
            key = entry.Key;
            return true;
        }
        key = default(K);
        return false;
    }
}

the usage is also so simple

int key = 0;
if (myDictionary.TryGetKey("twitter", out key))
{
    // successfully got the key :)
}



Link : http://stackoverflow.com/questions/4001908/get-dictionary-key-by-using-the-dictionary-value



[참조] https://www.dotnetperls.com/extension

저작자 표시 비영리 동일 조건 변경 허락
신고

'Programming > C#' 카테고리의 다른 글

C# 강의  (0) 2014.08.29
람다 식  (0) 2014.08.29
Get Dictionary key by using the dictionary value  (0) 2014.08.12
[C#] How to get/set using index for a Dictionary?  (0) 2014.08.06
NTP 서버에서 시간 가져오기(SNTP)  (0) 2014.07.14
C# 외부 프로그램 종료하기  (0) 2014.05.20
Posted by blueasa

댓글을 달아 주세요

public class YourClass
{
    private readonly IDictionary<string, string> _yourDictionary = new Dictionary<string, string>();

    public string this[string key]
    {
        // returns value if exists
        get { return _yourDictionary[key]; }

        // updates if exists, adds if doesn't exist
        set { _yourDictionary[key] = value; }
    }
}





class SampleCollection<T>
{
    // Declare an array to store the data elements. 
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code 
    // to use [] notation on the class instance itself. 
    // (See line 2 of code in Main below.)         
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets 
            // the corresponding element from the internal array. 
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer. 
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();

        // Use [] notation on the type.
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}
// Output: 
// Hello, World.


Link : http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

저작자 표시 비영리 동일 조건 변경 허락
신고

'Programming > C#' 카테고리의 다른 글

람다 식  (0) 2014.08.29
Get Dictionary key by using the dictionary value  (0) 2014.08.12
[C#] How to get/set using index for a Dictionary?  (0) 2014.08.06
NTP 서버에서 시간 가져오기(SNTP)  (0) 2014.07.14
C# 외부 프로그램 종료하기  (0) 2014.05.20
C# Keywords  (0) 2014.05.13
Posted by blueasa

댓글을 달아 주세요

Dictionary foreach

Programming/C# / 2012.04.25 12:04

KeyValuePair 를 이용한다


            Dictionary<String, Object> dic = new Dictionary<String, object>();
            dic.Add("String0", true);
            dic.Add("String1", 13);

            foreach (KeyValuePair<String, Object> p in dic)
            {
                Console.WriteLine(p);
            }




저작자 표시 비영리 동일 조건 변경 허락
신고
Posted by blueasa

댓글을 달아 주세요

You want to use Dictionary in your C# program for constant lookup times and to associate keys with values. Look at some examples of using Dictionary with Keys and KeyValuePair, as well as with classes and methods. This document has tips and examples for using Dictionary with keys and values using the C# programming language.

Dictionary provides fast lookup of elements.
Used when you have many different elements.
Found in the System.Collections.Generic namespace.
Specify the types of its keys and values.

Adding keys

To get started, let's add four keys with values to a Dictionary instance. Afterwards, we look inside the Dictionary using Visual Studio's debugger. You will see that the Dictionary is composed of separate keys and values. Here's the Dictionary code and then its internal view.

~~~ Program that uses Dictionary Add method (C#) ~~~

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> d = new Dictionary<string, int>();
        d.Add("cat", 2);
        d.Add("dog", 1);
        d.Add("llama", 0);
        d.Add("iguana", -1);
    }
}

Inside the Dictionary. Here's what the above code looks like in memory. It is represented by a collection of key and value pairs. The screenshot is worth looking at. This article is based on .NET 3.5 SP1, but the contents apply to other versions as well.

Dictionary internals

Looking up values

Here we see how you can check to see if a given string is present in a Dictionary with string keys. We look at more types of Dictionaries further on, but here is the ContainsKey method.

=== Program that uses ContainsKey (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> d = new Dictionary<string, int>();
        d.Add("apple", 1);
        d.Add("windows", 5);

        // See if Dictionary contains this string
        if (d.ContainsKey("apple")) // True
        {
            int v = d["apple"];
            Console.WriteLine(v);
        }

        // See if Dictionary contains this string
        if (d.ContainsKey("acorn"))
        {
            Console.WriteLine(false); // Nope
        }
    }
}

=== Output of the program ===

1

Note on efficiency. There is a more efficient method called TryGetValue on the Dictionary class, and you should definitely use it when possible. As its name implies, it tests for the key and then returns the value if it finds the key.

See TryGetValue Method.

KeyNotFoundException

If you are running into the KeyNotFoundException, you are accessing a key in your Dictionary that doesn't exist. Dictionary is not the same as Hashtable and you must test keys for existence first, with ContainsKey or TryGetValue.

See KeyNotFoundException Fix.

Understanding KeyValuePair

Hint: this is not in every beginner's C# book. When Dictionary, or any object that implements IDictionary, is used in a foreach loop, it returns an enumeration. In the case of Dictionary, this enumeration is in the form of KeyValuePairs.

See KeyValuePair Collection Hints.

Using foreach on Dictionary

Here we use foreach syntax and KeyValuePair generics in the foreach loop. With collections like Dictionary, we must always know the value types. With each KeyValuePair, there is a Key member and Value member.

=== Program that uses foreach on Dictionary (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Example Dictionary again
        Dictionary<string, int> d = new Dictionary<string, int>()
        {
            {"cat", 2},
            {"dog", 1},
            {"llama", 0},
            {"iguana", -1}
        };
        // Loop over pairs with foreach
        foreach (KeyValuePair<string, int> pair in d)
        {
            Console.WriteLine("{0}, {1}",
                pair.Key,
                pair.Value);
        }
        // Use var keyword to enumerate dictionary
        foreach (var pair in d)
        {
            Console.WriteLine("{0}, {1}",
                pair.Key,
                pair.Value);
        }
    }
}

=== Output of the program ===

cat, 2
dog, 1
llama, 0
iguana, -1

cat, 2
dog, 1
llama, 0
iguana, -1

Overview of the code. The code example declares and populates an example Dictionary. This Dictionary happens to indicate what animals we have and how many of them.

Using the foreach loop. It has a ShowDictionaryPair method. This method demonstrates the foreach loop and the KeyValuePair declaration. Pay careful attention to the syntax in the foreach loop. Each KeyValuePair has two members, pair.Key and pair.Value, which contain string keys and int values.

Using the var keyword. The final loop in the code shows how you can make the syntax for looping really simple by using the var keyword. This is not always desirable on some projects, however.

Getting all Dictionary keys

Here we use the Keys property and then look through each key and lookup the values. This method is slower but has the same results. Using the Keys collection and putting it in an array or List is very effective in other situations.

=== Program that gets Keys from Dictionary (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> d = new Dictionary<string, int>()
        {
            {"cat", 2},
            {"dog", 1},
            {"llama", 0},
            {"iguana", -1}
        };
        // Store keys in a List
        List<string> list = new List<string>(d.Keys);
        // Loop through list
        foreach (string k in list)
        {
            Console.WriteLine("{0}, {1}",
                k,
                d[k]);
        }
    }
}

=== Output of the program ===

cat, 2
dog, 1
llama, 0
iguana, -1

Benchmarking KeyValuePair usage

Using foreach on KeyValuePairs is several times faster than using Keys. This is probably because the Keys collection is not used. KeyValuePair allows us to simply look through each pair one at a time. This avoids lookups and using the garbage-collected heap for storage.

See Garbage Collection Visualizations.

=== Benchmark for KeyValuePair foreach loop ===

KeyValuePair: 125 ms
Note:         This loops through the pairs in the Dictionary.

Keys loop:    437 ms
Note:         This gets the Keys, then loops through them.
              It does another lookup for the value.

Note on the benchmark. The author made a small change to the Keys version for clarity and performance, so these figures are only general and apply to the previous version. Using KeyValuePair is most likely still faster.

Sorting your Dictionary values

If you need to sort the values in your Dictionary, you may be perplexed at first and wonder how to order the keys properly. Fortunately, I have an article about how to do this, although it is not optimal.

See Sort Dictionary Values.

Related collections

You will find other collections, such as SortedDictionary, in the base class libraries, BCL, available for you to use. However, my experience is that it is hard to get as good performance as with Dictionary.

See SortedDictionary.

Using different types in Dictionary

Dictionary in C# is a generic class, which means it requires you to specify a type for it to use. So, you can use an int key, just as easily as a string key. Here is an example of a Dictionary with int keys.

=== Program that uses int keys (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Use a dictionary with an int key.
        Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Add(100, "Bill");
        dict.Add(200, "Steve");
        // You can lookup the int in the dictionary.
        if (dict.ContainsKey(200))
        {
            Console.WriteLine(true);
        }
    }
}

=== Output of the program ===

True

Advanced features of Dictionary. For more advanced developers, you can use the GetHashCode() method and override it to create Dictionaries or hashes with the class. This can improve performance in those cases.

Enhancing lookup speed

To enhance lookup speed on your Dictionary, you can change the size of the keys you use. My research has shown that when you use shorter string keys, the lookup time is improved. This could create more collisions, so testing may be necessary.

Using Dictionary with LINQ

By using the ToDictionary method, which is an extension method on IEnumerable that will place the keys and values into a new Dictionary using lambda expressions.

=== Program that uses LINQ (C#) ===

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] arr = new string[]
        {
            "One",
            "Two"
        };
        var dict = arr.ToDictionary(item => item, item => true);
        foreach (var pair in dict)
        {
            Console.WriteLine("{0}, {1}",
                pair.Key,
                pair.Value);
        }
    }
}

=== Output of the program ===

One, True
Two, True

Explanation of the example. The above example uses ToDictionary, which resides in the System.Linq namespace, on the string[] array to create a lookup table where both strings can be accessed in constant time, O(1).

Using ContainsValue to find values

Dictionary also helpfully implements a method called ContainsValue. This method does not enjoy the constant-time lookup speed that ContainsKey has, however. It instead searches the entire collection, making it linear in complexity.

=== Program that uses ContainsValue (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> d = new Dictionary<string, int>();
        d.Add("cat", 1);
        d.Add("dog", 2);
        if (d.ContainsValue(1))
        {
            Console.WriteLine(true); // true
        }
    }
}

=== Output of the program ===

True

ContainsValue method. The above example will internally loop through all elements in the Dictionary until it finds the match, or there are no more to check. MSDN: "This method is an O(n) operation, where n is Count."

See ContainsValue Dictionary Example.

Clearing and counting

You can erase all the key/value pairs within your Dictionary by using the Clear() method, which accepts no parameters. Alternatively, you can assign the variable to null. The difference between Clear and null is not important for memory, as in either case the entries are garbage-collected. Internally, I see that Clear calls Array.Clear, which is not managed code.

Counting your Dictionary. The Count method on the Dictionary collection gives you an effective way of computing the total number of keys in the instance. This is much simpler than accessing the Keys property or looping over the Dictionary to count it. This Count property is covered in more detail on this site.

See Count Dictionary, Using Count Property.

Removing an entry

Here you want to eliminate an entry, not just by setting its value to null or string.Empty, but by also removing the key itself. Fortunately, you can use the Remove method.

~~~ Program that uses Remove (C#) ~~~

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> d = new Dictionary<string, int>();
        d.Add("cat", 1);
        d.Add("dog", 2);

        d.Remove("cat");     // Removes cat
        d.Remove("nothing"); // Doesn't remove anything
    }
}

Execution of the code. Running the code in Visual Studio, no exceptions are thrown, which means that when you remove a key that doesn't exist, nothing happens. However, Remove throws System.ArgumentNullException when it receives a null parameter.

Copying entire Dictionary

The Dictionary class has a useful constructor that allows you to easily copy all the values and keys in your Dictionary into a new Dictionary instance. You can write the logic yourself, but using this constructor improves code reuse and simplicity. This site has more information on the Dictionary copy constructor.

See Copy Dictionary.

Parameters and return values

It is also possible to use the Dictionary constructed type in the C# language as a parameter to methods or as a return value from methods or properties. Because the Dictionary type is defined as a class, it is always passed as a reference type, meaning only 32-64 bits will be copied on the method invocation. The same principles apply when copying a Dictionary return value from a method. You can find more information on Dictionary parameters on this site.

See Dictionary Parameter and Return Value.

Question

Should I use List or Dictionary?

I suggest you almost always use Dictionary when you need to do lookups. If you use List and you need to look up a key, your program may freeze if you happen to have a huge number of elements. In other words, if you use Dictionary, your program can recover from pathological, edge cases.

Using multiple variables in single key

You can sometimes use multiple variables in a key by creating a special function that transforms those variables into a string, serializing them. So, you could use the string "1,2" to mean the ints 1 and 2.

Initializing Dictionary at class level

Sometimes it is useful to have a Dictionary in your class that is allocated at the class level, not in a method or constructor. Additionally, if you have a static class then you should always initialize your Dictionary at the class level like this instead of the static constructor. Static constructors have performance penalties, which I have measured.

=== Program that uses Dictionary with class (C#) ===

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Example e = new Example();
        Console.WriteLine(e.GetValue());
    }
}

class Example
{
    Dictionary<int, int> _d = new Dictionary<int, int>()
    {
        {1, 1},
        {2, 3}, // <--
        {3, 5},
        {6, 10}
    };
    public int GetValue()
    {
        return _d[2]; // Example only
    }
}

=== Output of the program ===

3

Summary

In this article, we saw how you can use Dictionary with KeyValuePair to look through all pairs in the Dictionary. Additionally, we saw material on ContainsKey, which lets you check key existence. Finally, the author considers Dictionary one of the most interesting subjects in the programming world.

See Dictionary Articles.

© 2007-2010 Sam Allen. All rights reserved.


출처 : http://dotnetperls.com/dictionary-keys

저작자 표시 비영리 동일 조건 변경 허락
신고
Posted by blueasa

댓글을 달아 주세요

  1. 2012.02.11 08:38 신고 dormir  댓글주소  수정/삭제  댓글쓰기

    두 분 전 . 뒤로 이동 이 사이트를 읽을 !

  2. 2012.04.25 02:04 신고 Management Thesis  댓글주소  수정/삭제  댓글쓰기

    very nice blog and I really appreciate your hard work .. and I hope you update your blog daily

  3. 2014.05.07 05:09 신고 Mathew  댓글주소  수정/삭제  댓글쓰기

    awesome! Thanks for much! I understand!

1) Key, Value Binding
    comboBox.DataSource = new BindingSource(Dictionary, null);

2) Key Binding
    comboBox.DataSource = new BindingSource(Dictionary.Keys, null);

3) Value Binding
    comboBox.DataSource = new BindingSource(Dictionary.Values, null);


저작자 표시 비영리 동일 조건 변경 허락
신고
Posted by blueasa

댓글을 달아 주세요


예전 C++에서 사용한 STL의 map을 사용하고 싶었다..
  구글형한테 열심히 물어본결과 C#에는
Dictionary라는 map과 일치하는 라이브러리가 존재한단다..

  사용해보니 Key값과 Value값을 이용하는 아주 전형적인
map이다.
  내부 알고리즘은 안뜯어봐도 거기서 거기일듯 하다..
 
  한가지 다른건 STL map에서는 Key값을 모를때
iteraterfor문을 이용한 순차접근을 했다는것이고..
 
Dictionary에서는 KeyValuePair  foreach문을 이용한 순차접근을 해야한다는 것이다..

  다음은
DictionaryKey값을 모를때 순차접근을 위한 하나의 예이다..

  Dictionary<string,int> _DicSample;
  _DicSample= new Dictionary<string,int>();
  _DicSample.Add( "나이", 32 );
  _DicSample.Add( "키", 180 );

  foreach (KeyValuePair<string, int> each in _Dic )
  {
     string K = each.Key;
     int V = each.Value;
  }
  // 디버깅 해보면 foreach문이 총 2번돌고 K와 V값에는 "나이", 32 다음 "키" 180이 순차적으로
 들어간다.

  Key값을 알고있을때 Value값 찾는건 map과 동일한
  int age = _DicSample["나이"];
 // age에 32가 들어갈것이다.


출처 : http://incoinco.blog.me/70046275252

저작자 표시 비영리 동일 조건 변경 허락
신고
Posted by blueasa

댓글을 달아 주세요