2017-05-29 37 views
-7

是否可以在C#7中創建ValueTuple列表?如何創建ValueTuple列表?

這樣的:

List<(int example, string descrpt)> Method() 
{ 
    return Something; 
} 
+18

你爲什麼不嘗試一下呢? –

+3

因爲這是*返回指定元組列表所需的語法,所以我幾乎不願意downvote。爲什麼這樣問? –

+0

我想這個問題是關於不是Method的返回類型,而是關於丟失的** Something **。 – quetzalcoatl

回答

18

您正在尋找這樣的語法:

List<(int, string)> list = new List<(int, string)>(); 
list.Add((3, "test")); 
list.Add((6, "second")); 

您可以使用這樣的在你的情況下:

List<(int, string)> Method() => 
    new List<(int, string)> 
    { 
     (3, "test"), 
     (6, "second") 
    }; 

您還可以返回之前命名值:

List<(int Foo, string Bar)> Method() => 
    ... 

而且你可以接收值,而(重新)命名它們:

List<(int MyInteger, string MyString)> result = Method(); 
var firstTuple = result.First(); 
int i = firstTuple.MyInteger; 
string s = firstTuple.MyString; 
+0

thx Guilherme,回答我的問題 – ArthNRick

+0

它更好命名方法定義中的字段。 –

-2

此語法最好應用於c# 6,但可以在c# 7被使用。其他答案更加正確,因爲趨向於使用ValueTuple而不是此處使用的Tuple。你可以看到不同hereValueTuple

List<Tuple<int, string>> Method() 
{ 
    return new List<Tuple<int, string>> 
    { 
     new Tuple<int, string>(2, "abc"), 
     new Tuple<int, string>(2, "abce"), 
     new Tuple<int, string>(2, "abcd"), 
    }; 
} 
+1

根本不需要使用「Tuple」 –

+0

我當然更喜歡這個sintax,比其他人更可讀,更清晰。 – Gusman

+1

不知道爲什麼它得到了一些倒票,這是沒有錯的答案無論如何... –

4

當然,你可以這樣做:

List<(int example, string descrpt)> Method() => new List<int, string> { (2, "x") }; 

var data = Method(); 
Console.WriteLine(data.First().example); 
Console.WriteLine(data.First().descrpt);