Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a 2-d array into a dictionary object

Tags:

c#

linq

I have an array of type string that looks like this: "test1|True,test2|False,test3|False,test4|True". This is essentially a 2d array like so [test1][True] [test2][False] [test3][False] [test4][True].

I want to convert this into a dictionary<string,bool> using linq, something like:

Dictionary<string, bool> myResults = results.Split(",".ToCharArray).ToDictionary()

any ideas?

like image 200
Webcognoscere Avatar asked May 12 '10 09:05

Webcognoscere


People also ask

How do I turn an array into a 2D array?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping.

How do you declare a 2D array in C#?

Two-Dimensional Array Declaration Here's how we declare a 2D array in C#. int[ , ] x = new int [2, 3]; Here, x is a two-dimensional array with 2 elements. And, each element is also an array with 3 elements.

Can a dictionary value be an array?

The Dictionary object is used to hold a set of data values in the form of (key, item) pairs. A dictionary is sometimes called an associative array because it associates a key with an item. The keys behave in a way similar to indices in an array, except that array indices are numeric and keys are arbitrary strings.


2 Answers

var d = results.Split(',')
               .Select(row => row.Split('|'))
               .ToDictionary(srow => srow[0], srow => bool.Parse(srow[1]));
like image 156
Marcelo Cantos Avatar answered Nov 04 '22 06:11

Marcelo Cantos


First turn your string into a proper array:

String sData = "test1|True,test2|False,test3|False,test4|True";
String[] sDataArray = sData.Split(',');

Then you can process the String[] into a dictionary:

var sDict = sDataArray.ToDictionary(
        sKey => sKey.Split('|')[0], 
        sElement => bool.Parse(sElement.Split('|')[1])
    );

The ToDictionary method takes 2 functions which extract the key and element data from the each source array element.

Here, I've extracted each half by splitting on the "|" and then used the first half as the key and the second I've parsed into a bool to use as the element.

Obviously this contains no error checking so could fail if the source string wasn't comma separated, or if each element wasn't pipe separated. So be careful with where your source string comes from. If it doesn't match this pattern exactly it's going to fail so you'll need to do some tests and validation.

Marcelo's answer is similar, but I think it's a bit more elegant.

like image 37
Simon P Stevens Avatar answered Nov 04 '22 05:11

Simon P Stevens