Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Comma Separated Value to Dictionary

Tags:

c#

asp.net

linq

I'm trying to convert comma separated string to Dictionary

string text = "abc,xyz,pqr";

Output should be Dictionary<string, uint> with key as string from text & value as number starting from 0.

I tried below but it gives error:

text.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).ToDictionary(split => split[0], 0))`

I'm also not sure how to give incremental value so I tried with constant hard coded value for all keys in dictionary as shown above but its giving error too.

Any help with either constant value for all keys or with incremental value using linq is much helpful!!

like image 728
Freephone Panwal Avatar asked Mar 03 '26 17:03

Freephone Panwal


1 Answers

There are overloads of Select() which pass an index:

var dict = text.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
    .Select((str, idx) => new { str, idx })
    .ToDictionary(x => x.str, x => x.idx);
like image 200
Cory Nelson Avatar answered Mar 06 '26 07:03

Cory Nelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!