If I have a pipe separated list can I split them automatically into an array of GUID's?
So
"guid1|guid2"
and then Guid[] values = selectedValue.Split("|".ToCharArray());
would have been nice.
With the help of the function . Split(), we can split a string based on a certain delimiting character. It splits a string into an array of sub-strings. By default, it uses the whitespace character as the delimiter.
The Parse method trims any leading or trailing white space from input and converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table.
PowerShell uses the Split () function to split a string into multiple substrings. The function uses the specified delimiters to split the string into sub strings. The default character used to split the string is the whitespace.
Using the Split() and ToCharArray() methods of string object, you can convert string to array in PowerShell. The Split() method returns a string array and ToCharArray() method returns the character array.
Almost:
Guid[] values = selectedValue.Split('|').Select(s => Guid.Parse(s)).ToArray();
If any of the Guids isn't valid, this will throw a FormatException though.
If you want to ignore them, you can do what Jeremy suggest in the comments:
"9FE027E0-CF95-492F-821C-3F2EC9472657|bla|D94DF6DB-85C1-4312-9702-FB03A731A2B1"
.Split('|')
.Where(g => { Guid temp; return Guid.TryParse(g, out temp); })
.Select(g => Guid.Parse(g))
.ToArray()
Maybe this can be optimized further (We're essentially parsing each number twice) or simply ignored as the 97% premature optimizations that don't matter.
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