1

What I need is to be able to put in a SortedList a combination of two fields that are non-unique, but the pair is (like database composite keys).

More precisly, i have my list, and i want to be able to do this with it

Dim myList = New Generic.SortedList(Of String, String)
myList.add("aaa","aaa")
myList.add("aaa","bbb")
myList.add("bbb","bbb")
myList.add("bbb","aaa")

This would throw an exception as "an entry with the same key already exists"

I know i could make my own object and a list of that object, but is there anything that already exists for what i want to do?

Thanks

Shadowxvii
  • 1,080
  • 2
  • 12
  • 31
  • Well, the built-in thing is a `Tuple`, but it doesn't handle comparison for you. You'll have to make your own class. – Ry- Apr 16 '12 at 18:37
  • From what i see, i could do a `tuple(Of String, String)` but i would still need to do a `list(Of myTuple)` – Shadowxvii Apr 16 '12 at 18:50

1 Answers1

3

You could use the Lookup class. Jon Skeet provided a good answer on that subject. c# duplicate Keys in .NET dictionaries?

You first have to store them in a enumerable object though IEnumerable(Of (Tuple(Of String,String)) for example)

        Dim compositeKeys = New List(Of Tuple(Of String, String))
        compositeKeys.Add(New Tuple(Of String, String)("aaa", "aaa"))
        compositeKeys.Add(New Tuple(Of String, String)("aaa", "bbb"))
        compositeKeys.Add(New Tuple(Of String, String)("bbb", "aaa"))
        compositeKeys.Add(New Tuple(Of String, String)("bbb", "bbb"))

        Dim lookup = compositeKeys.ToLookup(Function(x) x.Item1)
        Dim aaaKeys = lookup("aaa") // 2 hits

For a specific lookup, there is always LINQ

Dim specificLookup = lookup("aaa").Where(Function(x) x.Item2 = "bbb").FirstOrDefault
Community
  • 1
  • 1
Alex
  • 7,901
  • 1
  • 41
  • 56