Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into array of GUID's

Tags:

c#

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.

like image 472
griegs Avatar asked Nov 11 '11 02:11

griegs


People also ask

How to split string into array in PowerShell?

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.

Can I convert a string to Guid?

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.

How to split the string in PowerShell?

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.

How to convert a string to an array in PowerShell?

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.


1 Answers

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.

like image 149
Michael Stum Avatar answered Oct 20 '22 21:10

Michael Stum