문제

I'm using C# 4.0. I want to store (string,string) pair using IDictionary. like below:

Dictionary<string, string> _tempDicData = new Dictionary<string, string>();
      _tempDicData.Add("Hello", "xyz");
      _tempDicData.Add("Hello", "aaa");
      _tempDicData.Add("Hello", "qwert");
      _tempDicData.Add("Hello", "foo");
      _tempDicData.Add("Hello", "pqr");
      _tempDicData.Add("Hello", "abc");

but got an error:

An item with the same key has already been added.

So How can I store same key in IDictionary?

도움이 되었습니까?

해결책

A class where u can add duplicated keys may look like the following:

class TDictionary<K, V>
{
    struct KeyValuePair
    {
        public K Key;
        public V Value;
    }

    private readonly List<KeyValuePair> fList = new List<KeyValuePair>();

    public void Add(K key, V value)
    {
        fList.Add(new KeyValuePair { Key = key, Value = value });
    }

    public List<V> this[K key]
    {
        get { return (from pair in fList where pair.Key.Equals(key) select pair.Value).ToList(); }
    }

    public List<K> Keys
    {
        get { return fList.Select(pair => pair.Key).ToList(); }
    }

    public List<V> Values
    {
        get { return fList.Select(pair => pair.Value).ToList(); }
    }
}

다른 팁

You cannot add the same item to IDictionary<K,T> more than once - that's the whole point of a dictionary, an associative container. But you can replace an existing one like this:

_tempDicData.Add("Hello", "xyz");
_tempDicData["Hello"] = "aaa";

and you can make a dictionary of lists if you need multiple items per key:

IDictionary<string,IList<string>> _tempDicData =
    new Dictionary<string,IList<string>>();
IList<string> lst = new List<string>();
lst.Add("xyz");
lst.Add("aaa");
_tempDicData.Add("Hello", lst);

When you do not know for sure if the list for a key exists or not, you can use this pattern to add new items:

IList<string> lst;
if (!_tempDicData.TryGetValue("Hello", out lst)) {
    _tempDicData.Add("Hello", lst);
}
lst.Add("xyz");
lst.Add("aaa");

You cannot have two items with the same key in a dictionary. However, you can have one item that is a itself a collection:

Dictionary<string, List<string>> _tempDicData = new Dictionary<string, List<string>>
{
    { "Hello", new List<string> { "xyz", "aa", "foo" },
};

If you go this way, you will have to be careful when accessing items because the underlying lists may or may not have been already created:

// WRONG: _tempDicData["Hello"] might not exist!
_tempDicData["Hello"].Add("bar");

// CORRECT:
if (!_tempDicData.ContainsKey("Hello")) {
    _tempDicData["Hello"] = new List<string>();
}
_tempDicData["Hello"].Add("bar");

You can not. The dictionary can only hold one item for every key. A dictionary is probably not the data structure you are looking for.

Create Dictionary<string,List<string>>.

Dictionary<string,List<string>> dict=new Dictionary<string,List<string>>();
dict.Add("hello",new List<string>());
dict["hello"].Add("foo");
dict["hello"].Add("bar");

You can't do it with a IDictionary. Try using NameValueCollection.

impossible, create own class with fields key value for this purpose

You can't?

You could use a Dictionary<string, List<string>> or, if you want a read-only solution, you can use the ToLookup extension method.

var lp = new[]
{
    Tuple.Create("Hello", "xyz"),
    Tuple.Create("Hello", "aaa"),
    Tuple.Create("Hello", "qwert"),
    Tuple.Create("Hello", "foo"),
    Tuple.Create("Hello", "pqr"),
    Tuple.Create("Hello", "abc"),
}.ToLookup(p => p.Item1, p => p.Item2);

foreach (var key in lp)
{
    foreach (var value in key)
    {
        Console.WriteLine("{0}: {1}", key.Key, value);
    }
}

Key has to be unique to search the values.

why that you will want to do that. the idea of dictionary is items by key and if it appers more then once that is not the key.

you can create dictionary of > but it's better for you to replan your needs.

I think you have to create your own class where you can add the same key several times. A dictionary is the wrong way to do this.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top