0

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?

0

3 Answers 3

5

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()
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, I like this better than my suggestion. Nice and concise. +1
Right answer. Of course 30 seconds of debugging on the part of the OP would have given him that answer.
i actually want only these values DC0000002 00:0c 564d6ae4-979 as a individual strings ..
@pratapk So extract the first, second, and third items from the list like your original code does.
0

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?

2 Comments

Your code has the same bug that the original code does.
Yep - so it does. Missed the space after the space. Will edit for accuracy - won't change the fact that @Sergey Berezovskiy's answer was more elegant.
0

You could use the TrimStart() function in your linq statement like:

decryptedList = decodePP.Split(';').Select(x => x.TrimStart().Split(' ')[1]).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.