Assignment Error in LINQ
I am changing string array into dictionary collection.
string str = "When everybody is somebody then no one is anybody";
char[] separation = { ' ', '.', ',' };
var splitted=str.Split(separation);
(Absolutely it is not a good design,but i wish to know the logic)
When i build query
var indexed = (from i in Enumerable.Range(1, splitted.Length)
from strn in splitted
select new { i, strn }).ToDictionary(x => x.i, x => x.strn);
I receive开发者_如何学运维d "Key already found in dictionary"
. I am supplying unique keys as enumerated
values.
No, you're not supplying unique keys. You're supplying:
1 When
2 When
3 When
...
9 When
1 everybody
2 everybody
etc
... so you'll be giving "1" as a key twice (then you'd supply "2" as a key again if you ever got that far).
What result are you actually trying to achieve? If it's: 1 -> When, 2 -> everybody etc then you want:
var indexed = splitted.Select((value, index) => new { value, index })
.ToDictionary(x => x.index + 1, x => x.value);
精彩评论