there some method equal list() of php in C#?
usage list() in PHP:
$array = array('foo','baa');
list($foo, $baa) = $array;
echo $foo; //foo
echo $baa; //baa
equivalent in javascript:
var arr = ['foo','baa'];
var foo;
var baa;
[foo, baa] = arr;
Thanks in advance!
There is no direct language equivalent in C#. While collection initializers can be used to construct the array, there is no way to extract elements directly.
This requires explicitly setting variables, ie:
var theArray = GetArrayFromSomewhere();
var foo = theArray[0];
var bar = theArray[1];
This is more similar to the original intention, though some might not like all the ceremony :
string a = null, b = null, c = null;
new ValList(v => a = v,
v => b = v,
v => c = v).SetFrom(new string[] { "foo", "bar" });
//here a is "foo", b will be "bar", and c is still null
And the simple helper class:
class ValList
{
private Action<string>[] _setters;
public ValList(params Action<string>[] refs)
{
_setters = refs;
}
internal void SetFrom(string[] values)
{
for (int i = 0; i < values.Length && i < _setters.Length; i++)
_setters[i](values[i]);
}
}
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