0

I need to store a value and its corresponding List of strings in a List. like

  Key   Value     
  2      2,3
  2      4,6
  4      3,5,6

 This should be in a list

Here i cant use a Dictionary because the same key might repeat. Anyone know how to it kindly help

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

4 Answers4

4

Use a Lookup. This is just like a dictionary, only it allows the same key multiple times.

Here are the docs. You have to use the .ToLookup extension method on your sequence to create one.

In your case, it seems like you'd need a ILookup<string, IList<string>> (or int instead of string, i don't know your data).

Here's how you can generate the lookup:

IEnumerable<KeyValuePair<string, IEnumerable<string>> myData = new[] {
    new KeyValuePair<string, IEnumerable<string>>("2", new[] { "2", "3" }),
    new KeyValuePair<string, IEnumerable<string>>("2", new[] { "4", "6" }),
    new KeyValuePair<string, IEnumerable<string>>("4", new[] { "3", "5", "6" }),
};
var myLookup = myData.ToLookup(item => item.Key, item => item.Value.ToList());
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
1

How can you distinguish between the two '2' keys? If you do not need to, then what about using a dictionary of lists of lists of int? the key is the key, and the value is a list of lists for all the duplicate keys.

Dictionary<int, List<List<int>>> map;

Like this

var map = new Dictionary<int, List<List<int>>>();

map[2] = new List<List<int>>();
map[2].Add(new List<int>(){ 2, 3});
map[2].Add(new List<int>(){ 4, 6});

map[4] = new List<List<int>>();
map[4].Add(new List<int>(){ 3, 5, 6});

foreach(var key in map.Keys)
{
    foreach(var lists in map[key])
    {
        Console.WriteLine("Key: {0}", key);
        foreach(var item in lists)
        {
            Console.Write(item);
        }
        Console.WriteLine();
    }
 }

If you do need to distinguish between the keys, then you need to provide a custom hashCode (override the GetHashCode() function) for a custom class or to find other types to be used as a key to guarantee uniqueness.

m1o2
  • 1,549
  • 2
  • 17
  • 27
1

Alternately, just keep it simple and make a class.

public class ClassNameHere
{
    public int Key { get; set; }
    public List<string> Values { get; set; }
}

Then use linq for lookups, etc.

var someList = new List<ClassNameHere>();
//add some data
var lookupResult = someList.Where(x=>x.Key == 2);
aw04
  • 10,857
  • 10
  • 56
  • 89
0

If you don't like (for some reasons) use Lookup how it suggest Lucas, and want to use List class, you may use following strange construction:

var list = new List<Tuple<string, List<string>>> {
     new Tuple<string, List<string>>("2", new List<string> {"2", "3"})
};

But, I think you should think twice before use it. It is better to use Lookup, of course.

Boris Parfenenkov
  • 3,219
  • 1
  • 25
  • 30