Fe2f7a39fccc30dc84a2ccd79dae2bc5

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!

1
2
int count = 0;
Dictionary<string,int> headers = line.Split(',').ToDictionary(y => y, y => count++);

Refactorings

No refactoring yet !

22e33503870d8e20493c4dd6b2f9767f

rikkus

October 8, 2009, October 08, 2009 19:58, permalink

1 rating. Login to rate!

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; });
F9a9ba6663645458aa8630157ed5e71e

Ants

October 10, 2009, October 10, 2009 00:51, permalink

No rating. Login to rate!

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; });

Your refactoring





Format Copy from initial code

or Cancel