How to convert a 2-d array into a dictionary object
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开发者_如何学编程?
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.
You could try something like this:
var resultsArray = results.Split(',');
var myResults = new Dictionary<string, bool>();
foreach (var str in resultsArray)
{
var parts = str.Split('|');
myResults.Add(parts[0], bool.Parse(parts[1]));
}
Something like this should work:
var fullString = "Test,True|Test2,False";
var query = from item in fullString.Split('|')
let splitted = item.Split(',')
let value = bool.Parse(splitted[1])
select new { Key = splitted[0], Value = value };
var dict = query.ToDictionary(pair => pair.Key, pair => pair.Value);
精彩评论