Kesandal
Kesandal

Reputation: 1303

Which collection type should I use?

I've three ListBoxes: lb1, lb2 and lb3.

Let's say in lb1 are 4 elements, in lb2 are 5 elements.

Each unique combination of (lb1 and lb2) can be assigned to a element in lb3.

Those combinations and associations I would like to store in a collection. My first though was to use a KeyValuePair with Key = (lb1Element1_lb2Element1), Value = lb3Element1.

But with this solution I will run into problems. Let's say I delete lb1Element1, there's no option(?) to delete all other combinations where lb1Element1 occurs from the KeyValuePair-List.

Which collection type would be the best in this case?

Thanks in advance John

Edit: All 3 ListBoxes are containing numbers.

Upvotes: 0

Views: 112

Answers (3)

RobH
RobH

Reputation: 3612

Why not create class for the key:

public class YourKey
{
    public int Item1 { get; private set; }
    public int Item2 { get; private set; }

    public YourKey(int item1, int item2)
    {
       this.Item1 = item1;
       this.Item2 = item2;
    }

    public override bool Equals(object obj)
    {
        YourKey temp = obj as YourKey;
        if (temp !=null)
        {
            return temp.Item1 == this.Item1 && temp.Item2 == this.Item2;
        }
        return false;
    }

    public override int GetHashCode()
    {
        int hash = 37;
        hash = hash * 31 + Item1;
        hash = hash * 31 + Item2;
        return hash;
    }
}

Then you can use this in a Dictionary<YourKey, int> to store all of the values.

This has the benefit of only being able to store one value of each combination of Item1 and Item2.

If you want to delete all entries in yourDictionary that have item 1 == 1:

var entriesToDelete = yourDictionary.Where(kvp => kvp.Key.Item1 == 1).ToList();
foreach (KeyValuePair<YourKey, int> item in entriesToDelete)
{
    yourDictionary.Remove(item.Key);
}

Upvotes: 0

Greg Oks
Greg Oks

Reputation: 2730

How about 2 dictionaries, 1 for lb1 and 1 for lb2:

Dictionary<string, Dictionary<string,string>>

First dic: the key is each lb1 value and the value is all the values of lb2 (dictionary where key and value are the same) Second dic: the key is each lb2 value and the value is all the values of lb1

If you delete option "x" from the lb2 list box then to find all the connected lb1 values of the deleted lb2 value, delete from the 1st dic all the pairs that have "x" as an lb2 value and then delete the whole "x" key from the 2nd dic:

Foreach(var lb1value in Dic2.ElementAt("x").value.keys)
  {
    Dic1.ElementAt("lb1value").
     value.RemoveAt("x");
  }

dic2.removeAt("x");

Upvotes: 1

Gabe
Gabe

Reputation: 50523

You could just use a Dictionary<string,string> for keyvalue which also provides the ability to Remove()

 Dictionary<string, string> items = new Dictionary<string, string>();

 items.Remove("mykey");

Upvotes: 1

Related Questions