Easy way to populate the dictionary <string, List <string>

Hail Guru, my goal is to create a dictionary of lists, is there a simpler technique?

I prefer List (t) to IEnumerable (t), so I chose a list dictionary over Ilookup or IGrouping.

The code works, but it seems like it's a dirty way to do something.

string[] files = Directory.GetFiles (@"C:\test"); Dictionary<string,List<string>> DataX = new Dictionary<string,List<string>>(); foreach (var group in files.GroupBy (file => Path.GetExtension (file))) { DataX.Add (group.Key, group.ToList()); } 
+8
c # linq
source share
1 answer

To do all this in LINQ, you can use ToDictionary() :

 string[] files = Directory.GetFiles (@"C:\test"); var DataX = files.GroupBy (file => Path.GetExtension (file)) .ToDictionary(g => g.Key, g => g.ToList()); 

or as Klaus points out below, you can do it at a time:

 var DataX = Directory.GetFiles (@"C:\test") .GroupBy (file => Path.GetExtension (file)) .ToDictionary(g => g.Key, g => g.ToList()); 
+12
source share

All Articles