Possible to initialize multiple variables from a tuple?

十年热恋 提交于 2019-12-01 14:39:59

问题


In some languages (such as PHP, Haskell, or Scala), you can assign multiple variables from tuples in a way that resembles the following pseudocode:

list(string value1, string value2) = tupleWithTwoValues;

I can't find a way to do this in C#, however, without writing longer, uglier code:

string firstValue = tupleWithTwoValues.Item1;
string secondValue = tupleWithTwoValues.Item2;

This two-line solution is obviously not the end of the world, but I'm always looking for ways to write prettier code.

Does anyone know a better way to do this?


回答1:


Valid up to C# 6:

No, this is not possible. There's no such language feature in C#.

If you think the following code:

string firstValue = tupleWithTwoValues.Item1;
string secondValue = tupleWithTwoValues.Item2;

is ugly, then you should reconsider using tuples at the first place.


UPDATE: As of C# 7, tuple deconstruction is now possible. See the documentation for more information.

See Jared's answer as well.




回答2:


This is now available in C# 7:

public (string first, string last) FullName()
{
    return ("Rince", "Wind");
}

(var first, var last) = FullName();

You can even use a single var declaration:

var (first, last) = FullName();

More on destructuring tuples in the official documentation.




回答3:


You can technically do this with a single statement, rather than two statements, using the following syntax, although the character count is almost identical.

string firstValue = tupleWithTwoValues.Item1
    , secondValue = tupleWithTwoValues.Item2;



回答4:


No this is not supported in C#, although others have suggested adding a feature like this (here and here).

It is supported by F#, however:

let (f, b) = ("foo", "bar")



回答5:


Yes it is possible in C#. You'll need to install the package Value.Tuple in your project. You can do like this

List<Tuple<string,string>>() lstTuple = GetYourTupleValue();
foreach(var item in lstTuple)
{
  (string Value1, string Value2 ) = item;
}
Console.WriteLine(item.Value1);



回答6:


when it comes to lists, you can do something like this:

var list = new List<string>{tuple.Item1, tuple.Item2};

(It's not that wordy) But for multiple variables, no. You can't do that.




回答7:


This is what I do:

public static TResult Select<T1, T2, TResult>(this Tuple<T1, T2> source, Func<T1, T2, TResult> selector)
{
    return selector(source.Item1, source.Item2);
}
// this allows us ...
GetAssociationAndMember().Select((associationId,memberId) => {
    // do things with the aptly named variables
});


来源:https://stackoverflow.com/questions/20892984/possible-to-initialize-multiple-variables-from-a-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!