1 2
int count = 0; Dictionary<string,int> headers = line.Split(',').ToDictionary(y => y, y => count++);
Refactorings
No refactoring yet !
rikkus
October 8, 2009, October 08, 2009 19:58, permalink
Do you mind me asking why you want each token mapped to its index?
1
line.Split(new[] {','}).Aggregate(new Dictionary<string, int>(), (d, s) => { d[s] = d.Keys.Count + 1; return d; });
Ants
October 10, 2009, October 10, 2009 00:51, permalink
LOL! Nieled's code actually returns ["A",0],["B",1],["C",2],["D",3] while Rikkus' code returns the requested ["A",1],["B",2],["C",3],["D",4].
Building on Rikkus' code I've added code to handle "", and "Alpha, , Charlie , , Echo". I arbitrarily chose to ignore empty strings, and to trim leading and trailing spaces on the strings.
Unfortunately, the code still can't handle "Amazon, \"Invisible, Inc.\", Jim's Carwash". Probably have to replace the Split() with some regular expression matcher.
Also what's suppose to happen if the line is "A,A,A" ? Is it suppose to be
a) ["A", 1],["A", 2],["A", 3]
b) ["A",1]
c) ["A",3]
d) exception
1 2
line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Aggregate(new Dictionary<string, int>(), (d, s) => { d[s.Trim()] = d.Keys.Count + 1; return d; });
Anyone up for the challenge of getting this down to one line of code? I could do it in ruby :)
"A,B,C,D"
should become
["A",1],["B",2]..etc
Good luck!