September 25, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Convert String to Dictionary using LINQ"
  1. Anonymous said...
    September 29, 2010 4:16 AM

    Nice! :-)

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions