I have a string with several fields separated by a specific character, something like this:
A,B,C
I want to split the string at the commas and assign each resulting field to its own string variable. In Perl I can do that elegantly like this:
my ($varA, $varB, $varC) = split (/,/, $string);
What is the simplest and most elegant way to achieve the same result in C#?
I know that I can split into an array:
string[] results = string.Split(',');
But then I would have to access the fields via their index, e.g. results[2]. That is difficult to read and error-prone - consider not having 3 buth 30 fields. For that reason I prefer having each field value in its own named variable.
I agree. Hiding the split in an Adapter class seems like a good approach and communicates your intent rather well:
public class MySplitter
{
public MySplitter(string split)
{
var results = string.Split(',');
NamedPartA = results[0];
NamedpartB = results[1];
}
public string NamedPartA { get; private set; }
public string NamedPartB { get; private set; }
}
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