tags:

views:

28

answers:

1

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 received "Key already found in dictionary" . I am supplying unique keys as enumerated values.

+1  A: 

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);
Jon Skeet
1 when , 2 Everybody ,3 is ,4 somebody,5 then ,6 nobody ,7 is ,8 anybody
udana
oh!!! Does it select all possible combinations (1,when),(2,when)... god !
udana
You did not supply any value for index,then how did you achieve the result ???? Is it compiler magic? Moreover no starting and ending range is specified!!! Quite amazing.Please ,let me know the process.
udana
Normally for integer we have to assign the initial value is won't it?
udana
The Select method is overloaded - I'm using the form that takes a `Func<TSource, int, TResult>`; it provides the index itself.
Jon Skeet
can we use any delegates inside Select( ) , i mean Fucn<> ,Predicate<>,Action< >,.... ?
udana
Most of LINQ uses `Func<...>`. The methods declare which delegate types they require. See the docs for System.Linq.Enumerable for details.
Jon Skeet