I have string
which I need to split()
and assign it's value into two variables. Is it possible for split()
to return tuple
instead of string[]
so I can do something like:
String myString = "hello=world" value, id = myString.Split('=');
I'm looking for some elegant solution.
split() returns a list while str. partition() returns a tuple . This is significant since a list is mutable while a tuple is not.
When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
The split() method in Python returns a list of the words in the string/line , separated by the delimiter string. This method will return one or more new strings. All substrings are returned in the list datatype.
To split string variables at each whitespace, we can use the split() function with no arguments. The syntax for split() function is split(separator, maxsplit) where the separator specifies the character at which the string should be split. maxsplit specifies the number of times the string has to be split.
If you can use C# 7 - you can use tuple deconstruction. If type has static or extension method named Deconstruct
with appropriate signature - this type can be deconstructed. So you can have extension method like this:
public static class Extensions { public static void Deconstruct<T>(this IList<T> list, out T first, out IList<T> rest) { first = list.Count > 0 ? list[0] : default(T); // or throw rest = list.Skip(1).ToList(); } public static void Deconstruct<T>(this IList<T> list, out T first, out T second, out IList<T> rest) { first = list.Count > 0 ? list[0] : default(T); // or throw second = list.Count > 1 ? list[1] : default(T); // or throw rest = list.Skip(2).ToList(); } }
And then you can deconstruct string array (which implements IList<string>
) with this syntax (you might need to add appropriate using
so that extension method above is reachable):
var line = "a=b"; var (first, second, _) = line.Split('='); Console.WriteLine(first); // "a" Console.WriteLine(second); // "b"
or
var line = "a=b"; var (first, (second, _)) = line.Split('='); Console.WriteLine(first); // "a" Console.WriteLine(second); // "b"
Which is quite close to what you need.
With just first extension method above (which deconstructs to first element and the rest) you can deconstruct to arbitrary length:
var (first, (second, _)) = line.Split('='); var (first, (second, (third, _))) = line.Split('='); var (first, rest) = line.Split('='); // etc
Second extension method is needed only if you want a little bit more convenient syntax for deconstruction of first 2 values (var (first, second, rest)
instead of var (first, (second, rest))
)
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