On Wed, 03 Sep 2008 09:05:32 -0700, CSharper <cs******@gmx.comwrote:
Yesterday I was working on a code where I need to split the parameters
and create dictionary from it. The string is something like the
following
name key1=value1 key2=value2
here is the code
string[][] pharsed = argument.Skip(1).Select(s =>
s.split(’=')).ToArray();
IDictionary<string, stringdictionary = new Dictionary<string,
string>();
foreach(string[] vaue in pharsed)
{
dictionary.add(vaue[0], vaue[1]);
}
Just want to know, is it possible to create the dictionary also in the
same line of code instead of doing it like I am trying?
I think so, sort of. Granted, I think the code you're using seems fine
as-is, but if you want to go whole-hog with the LINQ, here are a couple of
options I think would work for you:
IDictionary<string, stringdictionary = new Dictionary<string,
string>();
argument.Skip(1).Aggregate(delegate (string strIgnore, string strCur)
{
string[] rgstrKeyValue = strCur.Split('=');
dictionary.Add(rgstrKeyValue[0], rgstrKeyValue[1]);
return null;
});
Some might consider that an abuse of the Aggregate() method, but without a
ForEach(), it seems to do. Alternatively, you could do:
IDictionary<string, stringdictionary = new Dictionary<string,
string>();
argument.Skip(1).ToList().ForEach(delegate (string strCur)
{
string[] rgstrKeyValue = strCur.Split('=');
dictionary.Add(rgstrKeyValue[0], rgstrKeyValue[1]);
});
Maybe a bit more expressive, at the cost of converting the input to a
List<stringfirst.
Note that in neither case is it actually a one-liner. I suppose you could
make it briefer by doing the Split() twice, but I just can't bring myself
to do that just to make shorter code, so the above winds up having to
cache the Split() result in a local.
Pete