简体   繁体   中英

Easy way to Populate a Dictionary<string,List<string>>

Greetings Guru's, my objective is to create a Dictionary of Lists, does a simpler technique exist?

I prefer the List(t) to IEnumerable(t) which is why I chose the Dictionary of Lists over Ilookup or IGrouping.

The code works but it seems like a messy way of doing things.

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());
}

To do it all 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 below out you can do this all in one go:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM