Programing

다중 값 사전

crosscheck 2020. 10. 29. 07:51
반응형

다중 값 사전


C #에서 다중 값 사전을 어떻게 만들 수 있습니까?

Dictionary<T,T,T>를 들어 첫 번째 T는 키이고 다른 두 개는 값입니다.

그래서 이것은 가능할 것입니다 : Dictionary<int,object,double>

감사


Pair<TFirst, TSecond>유형을 만들고이를 가치로 사용하십시오.

C # in Depth 소스 코드에 예제가 있습니다 . 단순화를 위해 여기에서 재현 :

using System;
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond>
    : IEquatable<Pair<TFirst, TSecond>>
{
    private readonly TFirst first;
    private readonly TSecond second;

    public Pair(TFirst first, TSecond second)
    {
        this.first = first;
        this.second = second;
    }

    public TFirst First
    {
        get { return first; }
    }

    public TSecond Second
    {
        get { return second; }
    }

    public bool Equals(Pair<TFirst, TSecond> other)
    {
        if (other == null)
        {
            return false;
        }
        return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&
               EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
    }

    public override bool Equals(object o)
    {
        return Equals(o as Pair<TFirst, TSecond>);
    }

    public override int GetHashCode()
    {
        return EqualityComparer<TFirst>.Default.GetHashCode(first) * 37 +
               EqualityComparer<TSecond>.Default.GetHashCode(second);
    }
}

값을 함께 그룹화하려는 경우 간단한 구조체 또는 클래스를 만들어 사전의 값으로 사용할 수있는 좋은 기회가 될 수 있습니다.

public struct MyValue
{
    public object Value1;
    public double Value2;
}

그럼 당신은 당신의 사전을 가질 수 있습니다

var dict = new Dictionary<int, MyValue>();

한 단계 더 나아가 필요한 특수 작업을 처리 할 자체 사전 클래스를 구현할 수도 있습니다. 예를 들어 int, object 및 double을 허용하는 Add 메서드를 원할 경우

public class MyDictionary : Dictionary<int, MyValue>
{
    public void Add(int key, object value1, double value2)
    {
        MyValue val;
        val.Value1 = value1;
        val.Value2 = value2;
        this.Add(key, val);
    }
}

then you could simply instantiate and add to the dictionary like so and you wouldn't have to worry about creating 'MyValue' structs:

var dict = new MyDictionary();
dict.Add(1, new Object(), 2.22);

Dictionary<T1, Tuple<T2, T3>>

Edit: Sorry - I forgot you don't get Tuples until .NET 4.0 comes out. D'oh!


I think this is quite overkill for a dictionary semantics, since dictionary is by definition is a collection of keys and its respective values, just like the way we see a book of language dictionary that contains a word as the key and its descriptive meaning as the value.

But you can represent a dictionary that can contain collection of values, for example:

Dictionary<String,List<Customer>>

Or a dictionary of a key and the value as a dictionary:

Dictionary<Customer,Dictionary<Order,OrderDetail>>

Then you'll have a dictionary that can have multiple values.


I don't think you can do that directly. You could create a class containing both your object and double and put an instance of it in the dictionary though.

class Pair
{
    object obj;
    double dbl;
}

Dictionary<int, Pair> = new Dictionary<int, Pair>();

If the values are related, why not encapsulate them in a class and just use the plain old Dictionary?


You describe a multimap.

You can make the value a List object, to store more than one value (>2 for extensibility).

Override the dictionary object.


I solved Using:

Dictionary<short, string[]>

Like this

Dictionary<short, string[]> result = new Dictionary<short, string[]>();
result.Add(1,
           new string[] 
                    { 
                    "FirstString",
                    "Second"
                    }
                );
        }
return result;

I know this is an old thread, but - since it's not been mentioned this works

  Dictionary<string, object> LookUp = new Dictionary<string, object>();
  LookUp.Add("bob", new { age = "23", height = "2.1m", weight = "110kg"});
  LookUp.Add("jasper", new { age = "33", height = "1.75m", weight = "90kg"});
  foreach(KeyValuePair<string, object> entry in LookUp )
  {
      object person = entry.Value;
      Console.WriteLine("Person name:" + entry.Key + " Age: "  + person.age);          
  }

참고URL : https://stackoverflow.com/questions/569903/multi-value-dictionary

반응형