Convert String to Dictionary using LINQ

We were working on a requirement where we had a string containing key-value pairs as shown below:

string htmlStr = "[Emp=1][Dept=2][Age=35][Sex=M]";

We had to convert this string to a Dictionary in the simplest possible way. Here’s how it can be done using Enumerable.ToDictionary()

C#


public static void Main()
{
string htmlStr = "[Emp=1][Dept=2][Age=35][Sex=M]";
string[] arr = htmlStr.Split(new[] { '[', ']' },
StringSplitOptions.RemoveEmptyEntries);
// convert to a Dictionary
var dict = arr
.Select(x => x.Split('='))
.ToDictionary(i => i[0], i => i[1]);
}

VB.NET (Converted Code)


Public Shared Sub Main()
Dim htmlStr As String = "[Emp=1][Dept=2][Age=35][Sex=M]"
Dim arr() As String = htmlStr.Split( { "["c, "]"c }, StringSplitOptions.RemoveEmptyEntries)
' convert to a Dictionary
Dim dict = arr.Select(Function(x) x.Split("="c)).ToDictionary(Function(i) i(0), Function(i) i(1))
End Sub

As you can see, we first split the string and then use the ToDictionary method to convert the split string into a Dictionary object

OUTPUT

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

2 comments:

Anonymous said...

Nice! :-)

José said...

Thanks a lot!

Nice and really helpful!