Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add to C# dictionary: cannot convert from 'string' to 'System.Collections.Specialized.NameValueCollection'

Tags:

c#

I have a source of data which contains 3 different values like below,

List<Configuration> lst = new List<Configuration>
        {
            new Configuration{Name="A", Config="X", Value="1"},
            new Configuration{Name="A", Config="X", Value="2"},
            new Configuration{Name="B", Config="Y", Value="2"}
        };

 public class Configuration
{
    public string Name { get; set; }
    public string Config { get; set; }
    public string Value { get; set; }
}

Here I want to iterate to the entire source and want to keep "Name" value as a KEY and "Config" & "Value" into a "NameValueCollection".

For this I am taking a dictionary like below,

var config = new Dictionary<string, NameValueCollection>();

But while adding to this dictionary I m encounter 2 issues,

foreach(var c in lst)
        {
            config.Add(c.Name, new NameValueCollection { c.Config, c.Value });
        }
  1. Duplicate key (Name="A")
  2. this line giving error, new NameValueCollection { c.Config, c.Value });

Note - I want both 1 and 2 for X (in case of of duplicate key)

Is there any better C# collection or how to resolve above error.

Thanks!

like image 884
user584018 Avatar asked Apr 26 '17 08:04

user584018


1 Answers

You can use dictionary of lookups (it represents a collection where key is mapped to multiple values):

var config = lst.GroupBy(cfg => cfg.Name)
                .ToDictionary(g => g.Key, 
                              g => g.ToLookup(cfg => cfg.Config, cfg => cfg.Value));

Type of config will be

Dictionary<string, ILookup<string, string>>

Accessing values:

config["A"]["X"] // gives you IEnumerable<string> with values ["1","2"]
like image 108
Sergey Berezovskiy Avatar answered Oct 19 '22 23:10

Sergey Berezovskiy