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";
Console.WriteLine(
mapping
linq...expression...for...test1...here
);
Console.WriteLine(
mapping
linq...expression...for...test2...here
);
should print
description of label1
just a label
There's got to be an easier/shorter way:
ReplyDeleteConsole.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);
This will just give you a dictionary with the values updated like you described :)
ReplyDeletevar fixe = (from k in map
select new
{
k.Key,
Value = (k.Key.StartsWith("label")) ? "description of " + k.Key : k.Value
}).ToDictionary(k => k.Key, k => k.Value);
a small fixe..
ReplyDeletevar fixe= (from k in mapping
select new
{
k.Key,
Value = (k.Key.StartsWith("label")) ? "description of " + k.Key : k.Key
}).ToDictionary(k => k.Key, k => k.Value);