The below logic is working fine. But is there any way to optimize this logic ?
I have a string1, string2,...,stringn
and values of each strings are
string1 = "s1k1-s1k2-s1k3-....-s1kn | s1v1-s1v2-s1v3-....-s1vn";
string2 = "s2k1-s2k2-s2k3-....-s2kn | s2v1-s2v2-s2v3-....-s2vn";
.............
stringn = "snk1-snk2-snk3-....-snkn | snv1-snv2-snv3-....-snvn";
Now, I want to populate the Dictionary<string, string>()
with the key and values as follows.
var dict = new Dictionary<string, string>();
dict.Add(s1k1, s1v1);
dict.Add(s1k2, s1v2);
:
:
dict.Add(snkn, snvn);
Below is my sample code:
string string1 = "s1k1-s1k2-s1k3-s1kn|s1v1-s1v2-s1v3-s1vn";
string string2 = "s2k1-s2k2-s2k3-s2kn|s2v1-s2v2-s2v3-s2vn";
string stringn = "snk1-snk2-snk3-snkn|snv1-snv2-snv3-snvn";
var dict = new Dictionary<string, string>();
new List<string> { string1, string2, stringn }.ForEach(str =>
{
var strSplit = str.Split('|');
var strKeys = strSplit[0].Split('-');
var strValues = strSplit[1].Split('-');
strKeys.Zip(strValues, (key, value) => new { key, value }).ToList().ForEach(filed => dict.Add(filed.key, filed.value));
});
Is it possible to optimize this code interms of Speed and Readability.
feedback on a specific _working_ piece of code from your project
- see the FAQ. Code that has gross syntax and algorithm errors is not "working code". (I personally accept pseudo-code. Others don't.) After you fixed it your code is still missing at least a);
at the end and it still does not fill the dictionary, but that is good enough for me since you are new around here. I removed the -1. – ANeves Oct 19 '12 at 18:49Zip()
to perform side effects (add items to an external dictionary). Not only that, it is never performed because the result of the zippingtemp
is never iterated over which would make it work. However, I would very strongly advise you or anyone from ever doing stuff like that. It will only lead to headaches. – Jeff Mercado Oct 19 '12 at 18:57