Programing

사전에 추가하는 다양한 방법

lottogame 2020. 9. 2. 20:35
반응형

사전에 추가하는 다양한 방법


Dictionary.add(key, value)의 차이점은 무엇입니까 Dictionary[key] = value?

ArgumentException중복 키를 삽입 할 때 마지막 버전이 던지지 않는다는 것을 알았는데 첫 번째 버전을 선호하는 이유가 있습니까?

편집 : 누구든지 이것에 대한 정보의 권위있는 출처를 가지고 있습니까? 나는 MSDN을 시도했지만 항상 야생 거위 추적입니다 :(


성능은 거의 100 % 동일합니다. Reflector.net에서 클래스를 열어 확인할 수 있습니다.

This 인덱서입니다.

public TValue this[TKey key]
{
    get
    {
        int index = this.FindEntry(key);
        if (index >= 0)
        {
            return this.entries[index].value;
        }
        ThrowHelper.ThrowKeyNotFoundException();
        return default(TValue);
    }
    set
    {
        this.Insert(key, value, false);
    }
}

그리고 이것은 Add 메서드입니다.

public void Add(TKey key, TValue value)
{
    this.Insert(key, value, true);
}

다소 길기 때문에 전체 Insert 메서드를 게시하지는 않지만 메서드 선언은 다음과 같습니다.

private void Insert(TKey key, TValue value, bool add)

함수에서 더 아래로 내려 가면 다음과 같은 일이 발생합니다.

if ((this.entries[i].hashCode == num) && this.comparer.Equals(this.entries[i].key, key))
{
    if (add)
    {
        ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
    }

키가 이미 존재하는지 확인하고 존재하고 매개 변수 add가 true이면 예외를 발생시킵니다.

따라서 모든 목적과 의도에 대해 성능은 동일합니다.

다른 몇 가지 언급과 마찬가지로 동일한 키를 두 번 추가하려는 시도에 대해 확인이 필요한지 여부에 관한 것입니다.

긴 게시물에 대해 죄송합니다. 괜찮기를 바랍니다.


첫 번째 버전은 새 KeyValuePair를 사전에 추가하여 키가 이미 사전에 있으면 던집니다. 두 번째는 인덱서를 사용하여 키가없는 경우 새 쌍을 추가하지만 사전에 이미있는 경우 키 값을 덮어 씁니다.

IDictionary<string, string> strings = new Dictionary<string, string>();

strings["foo"] = "bar";          //strings["foo"] == "bar"
strings["foo"] = string.Empty;   //strings["foo"] == string.empty
strings.Add("foo", "bar");       //throws     

Dictionary.Add(key, value)Dictionary[key] = value다른 목적을 가지고 :

  • Add메서드를 사용하여 새 키 / 값 쌍 추가 하면 기존 키가 대체되지 않습니다 ( ArgumentException가 발생 함).
  • 키가 사전에 이미 있는지 여부를 신경 쓰지 않는 경우 인덱서를 사용합니다. 즉, 키가 사전에 없으면 키 / 값 쌍을 추가하고 키가 이미 있으면 지정된 키의 값을 바꿉니다. 사전에.

먼저 질문에 답하려면 사전의 목적과 기본 기술을 살펴 봐야합니다.

DictionaryKeyValuePair<Tkey, Tvalue>각 값이 고유 키로 표시되는 목록입니다 . 좋아하는 음식 목록이 있다고 가정 해 보겠습니다. 각 값 (음식 이름)은 고유 한 키 (위치 =이 음식을 얼마나 좋아하는지)로 표시됩니다.

예제 코드 :

Dictionary<int, string> myDietFavorites = new Dictionary<int, string>()
{
    { 1, "Burger"},
    { 2, "Fries"},
    { 3, "Donuts"}
};

Let's say you want to stay healthy, you've changed your mind and you want to replace your favorite "Burger" with salad. Your list is still a list of your favorites, you won't change the nature of the list. Your favorite will remain number one on the list, only it's value will change. This is when you call this:

/*your key stays 1, you only replace the value assigned to this key
  you alter existing record in your dictionary*/
myDietFavorites[1] = "Salad";

But don't forget you're the programmer, and from now on you finishes your sentences with ; you refuse to use emojis because they would throw compilation error and all list of favorites is 0 index based.

Your diet changed too! So you alter your list again:

/*you don't want to replace Salad, you want to add this new fancy 0
  position to your list. It wasn't there before so you can either define it*/
myDietFavorites[0] = "Pizza";

/*or Add it*/
myDietFavorites.Add(0, "Pizza");

There are two possibilities with defining, you either want to give a new definition for something not existent before or you want to change definition which already exists.

Add method allows you to add a record but only under one condition: key for this definition may not exist in your dictionary.

Now we are going to look under the hood. When you are making a dictionary your compiler make a reservation for the bucket (spaces in memory to store your records). Bucket don't store keys in the way you define them. Each key is hashed before going to the bucket (defined by Microsoft), worth mention that value part stays unchanged.

I'll use the CRC32 hashing algorithm to simplify my example. When you defining:

myDietFavorites[0] = "Pizza";

What is going to the bucket is db2dc565 "Pizza" (simplified).

When you alter the value in with:

myDietFavorites[0] = "Spaghetti";

You hash your 0 which is again db2dc565 then you look up this value in your bucket to find if it's there. If it's there you simply rewrite the value assigned to the key. If it's not there you'll place your value in the bucket.

When you calling Add function on your dictionary like:

myDietFavorite.Add(0, "Chocolate");

You hash your 0 to compare it's value to ones in the bucket. You may place it in the bucket only if it's not there.

It's crucial to know how it works especially if you work with dictionaries of string or char type of key. It's case sensitive because of undergoing hashing. So for example "name" != "Name". Let's use our CRC32 to depict this.

Value for "name" is: e04112b1 Value for "Name" is: 1107fb5b


Yes, that is the difference, the Add method throws an exception if the key already exists.

The reason to use the Add method is exactly this. If the dictionary is not supposed to contain the key already, you usually want the exception so that you are made aware of the problem.


Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.

I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.

The dict[key] = value represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.


One is assigning a value while the other is adding to the Dictionary a new Key and Value.

참고URL : https://stackoverflow.com/questions/1838476/different-ways-of-adding-to-dictionary

반응형