Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent to list() of php in C#

Tags:

arrays

c#

.net

list

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!

like image 227
The Mask Avatar asked Aug 17 '11 00:08

The Mask


2 Answers

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];
like image 139
Reed Copsey Avatar answered Nov 05 '22 02:11

Reed Copsey


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]);
    }
}
like image 34
Yoni Shalom Avatar answered Nov 05 '22 02:11

Yoni Shalom