Reputation: 17691
I am trying to split this string
string s = "sn DC0000002; mac 00:0c; uuid 564d6ae4-979";
I need to get these values from above string "DC0000002" , "00:0c" , "564d6ae4-979"
For this I have tried below query but not able to able to get last two values I mean these two values ("00:0c" , "564d6ae4-979")
Below is the query for splitting
List<string> decryptedList = new List<string>();
decryptedList = decodePP.Split(';').Select(x => x.Split(' ')[1]).ToList();
orgSNo = decryptedList[0]; //Output - DC0000002
orgMacID = decryptedList[1];// output - mac // this is wrong need to get value
orgUUID = decryptedList[2]; //output - uuid // this is also wrong
Would anyone please help on this query how extract values from the above string using LINQ query in a single shot?
Upvotes: 0
Views: 2117
Reputation: 51
You could use the TrimStart() function in your linq statement like:
decryptedList = decodePP.Split(';').Select(x => x.TrimStart().Split(' ')[1]).ToList();
Upvotes: 0
Reputation: 1585
Why do you need to use Linq. The string split would seem to do the trick?
string[] keyValuePairs = s.Split(';');
foreach(string pair.Trim() in keyValuePairs)
{
string key = pair.Split(' ')[0].Trim();
string value = pair.Split(' ')[1].Trim();
}
That's only a stab at the code - it may not compile, but you get the idea?
Upvotes: 0
Reputation: 236208
Just trim substrings which you get after first split:
decodePP.Split(';').Select(x => x.Trim().Split(' ')[1]).ToList();
You get incorrect results, because first split gives you
[ "sn DC0000002", " mac 00:0c", " uuid 564d6ae4-979" ]
As you can see, items except first one have leading whitespace.
Alternative solution - you can use StringSplitOptions.RemoveEmptyEntries
parameter to skip empty substrings
str.Split(';')
.Select(x => x.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1])
.ToList()
Upvotes: 5