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 });
}
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!
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With