If you can use C # 7, you can use tuple deconstruction. If the type has a static or expansion method named Deconstruct with the corresponding signature, this type can be deconstructed. So you can have an 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);
And then you can decompose the string array (which implements IList<string> ) with this syntax (you may need to add the appropriate using so that the extension method above is available):
var line = "a=b"; var (first, second, _) = line.Split('='); Console.WriteLine(first);
or
var line = "a=b"; var (first, (second, _)) = line.Split('='); Console.WriteLine(first);
This is pretty close to what you need.
Using only the first extension method above (which deconstructs the first element and the rest) you can deconstruct an arbitrary length:
var (first, (second, _)) = line.Split('='); var (first, (second, (third, _))) = line.Split('='); var (first, rest) = line.Split('=');
The second extension method is only necessary if you want a slightly more convenient syntax for deconstructing the first two values ââ( var (first, second, rest) instead of var (first, (second, rest)) )
source share