Possible to initialize multiple variables from a tuple?

前端 未结 7 469
孤独总比滥情好
孤独总比滥情好 2021-01-17 10:17

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(stri         


        
相关标签:
7条回答
  • 2021-01-17 10:40

    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")
    
    0 讨论(0)
  • 2021-01-17 10:43

    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.

    0 讨论(0)
  • 2021-01-17 10:45

    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.

    0 讨论(0)
  • 2021-01-17 10:47

    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.

    0 讨论(0)
  • 2021-01-17 10:54

    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
    });
    
    0 讨论(0)
  • 2021-01-17 10:56

    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);
    
    0 讨论(0)
提交回复
热议问题