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?
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.
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.
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.
var d = results.Split(',')
.Select(row => row.Split('|'))
.ToDictionary(srow => srow[0], srow => bool.Parse(srow[1]));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With