Friday, September 11, 2009

C# Puzzle No.19 (intermediate)

Suppose we have a mapping between two sets of labels.

Dictionary<string, string> mapping = new Dictionary<string, string>();
 mapping.Add( "label1", "description of label1" );
 mapping.Add( "label2", "description of label2" );
 mapping.Add( "label3", "description of label3" );
 mapping.Add( "label4", "description of label4" );

If we get a label from the set of keys, we have to change it into its counterpart. For example "label1" should become "description of label1" etc.

If we get any other label, we leave it with no changes. So "just a label" should remain as "just a label".

Your goal is to write a single LINQ expression that does the job. Specifically

string test1 = "label1";
string test2 = "just a label";



should print

description of label1
just a label
on the console.


brian said...

There's got to be an easier/shorter way:

Console.WriteLine(mapping.Where<KeyValuePair<string, string>>(f => f.Key == test1).DefaultIfEmpty<KeyValuePair<string, string>>(new KeyValuePair<string, string>("", test2)).FirstOrDefault<KeyValuePair<string,string>>().Value);

Console.WriteLine(mapping.Where<KeyValuePair<string, string>>(f =< f.Key == test2).DefaultIfEmpty<KeyValuePair<string, string>>(new KeyValuePair<string, string>("", test2)).FirstOrDefault<KeyValuePair<string, string>>().Value);

Caelan said...

This will just give you a dictionary with the values updated like you described :)

var fixe = (from k in map
select new
Value = (k.Key.StartsWith("label")) ? "description of " + k.Key : k.Value
}).ToDictionary(k => k.Key, k => k.Value); said...

a small fixe..
var fixe= (from k in mapping
select new
Value = (k.Key.StartsWith("label")) ? "description of " + k.Key : k.Key
}).ToDictionary(k => k.Key, k => k.Value);