Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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());
}
like image 862
zion Avatar asked Feb 16 '11 15:02

zion


People also ask

What is a dictionary of strings and lists?

A string is a sequence of characters. A list a sequence of values which can be characters, integers or even another list (referred to as a nested list). A dictionary is a more general version of a list and is made up a set of keys and values where there is a mapping between a given key and its corresponding value.

How to add list data to dictionary in c#?

Save this question. Show activity on this post. List<string> key = new List<string>(); List<long> val = new List<long>(); List<long> tempList = new List<long>(); Dictionary<string, List<long>> testList = new Dictionary<string, List<long>>(); key.

Can you use a list as a key for a dictionary C#?

Rate me: A relatively safe, simple, yet high performance technique for using lists as dictionary keys. Using collections as dictionary keys is sometimes necessary, but it can be a performance killer and unsafe.


1 Answers

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());
like image 80
Rup Avatar answered Oct 30 '22 22:10

Rup