Reputation: 14672
The First Dictionary
is like
Dictionary<String, String> ParentDict = new Dictionary<String, String>();
ParentDict.Add("A_1", "1");
ParentDict.Add("A_2", "2");
ParentDict.Add("B_1", "3");
ParentDict.Add("B_2", "4");
ParentDict.Add("C_1", "5");
i need to convert this into a new Dictionary<String, Dictionary<String,String>>
The result will contain
Key Value
Key Value
_________________________________________________
"A" "A_1" "1"
"A_2" "2"
"B" "B_1" "1"
"B_2" "2"
"C" "C_1" "1"
Now i'm using nested for loop
to do this.
How can i do this using LNQ
or LAMBDA Expression
?
Upvotes: 1
Views: 773
Reputation: 48066
The reason to do this I suspect is because you need to be able to lookup all entries for a particular key-letter. In that case, a Lookup
is a better match, generally:
var letterLookup = ParentDict.ToLookup(kv=>kv.Key[0]);
Usable like this:
//letterLookup['A'] is an IEnumerable<KeyValuePair<string,string>>...
Console.WriteLine(string.Join(", ",
letterLookup['A'].Select(kv=>kv.ToString()).ToArray()
)); // [A_1, 1], [A_2, 2]
Console.WriteLine(new XElement("root",
letterLookup['B'].Select(kv=>new XElement(kv.Key,kv.Value))
));// <root><B_1>3</B_1><B_2>4</B_2></root>
Console.WriteLine(letterLookup['B'].Any()); //true
Console.WriteLine(letterLookup['Z'].Any()); //false
The advantage of a lookup over a dictionary is that it may contain multiple values for any given key (unlike a dictionary), and that it has a consistent API if a certain key is absent: it then returns the empty enumerable, whereas a dictionary containing enumerables might either throw KeyNotFoundException, or return null, or return the empty enumerable, all depending on how you created it.
Upvotes: 1
Reputation: 43523
var result = ParentDict.GroupBy(p => p.Key[0].ToString())
.ToDictionary(g => g.Key, g => g.ToDictionary(x => x.Key, x => x.Value));
Upvotes: 5
Reputation: 46008
Try:
var result = from p in ParentDict
group p by p.Key[0] into g
select new { Key = g.Key, Value = g };
This should give you a list of { Key, Value }, where Key will be "A", "B", "C", etc, and Value will be an original instance of KeyValuePair from ParentDict.
You can find more LINQ sample queries on this MSDN page: 101 Linq Samples
Upvotes: 1