Linq recipe #1 combining two enums into a single dictionary

// Using Linq, ignore problems with jaggies

List<int> keys = new List<int> { 1, 2, 3, 4, 5 };           

List<string> data = new List<string> { "a", "b", "c", "d","e" };

 

Dictionary<int,string> combo = (from k in keys

            join d in data on keys.FindIndex(x => x==k) equals data.FindIndex(x2 => x2==d)                           

            select new {Key=k, Value=d} ).ToDictionary(de=>de.Key, de=>de.Value);

foreach (var i in combo)

{

    System.Diagnostics.Debug.WriteLine(i.Key + "," + i.Value);

}

 

// Using lamda expression, doesn’t allow jaggies

Dictionary<int, string> UrisByProject = new Dictionary<int, string>();

List<int> nonZeroProjectIds = new List<int>() { 1, 2, 3, 4,5 };

List<string> urisForTheImage = new List<string>() { "a", "b", "c", "d", "e" };

nonZeroProjectIds.ForEach(p => UrisByProject.Add(p, urisForTheImage[nonZeroProjectIds.FindIndex(t => t == p)]));

foreach (var i2 in UrisByProject)

{

    System.Diagnostics.Debug.WriteLine(i2.Key + "," + i2.Value);

}

Advertisements
This entry was posted in Linq. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s