C# 如何创建元组数组?

C# 如何创建元组数组?,c#,C#,我知道要在C#中创建元组,我们使用以下格式: Tuple <int,int>from = new Tuple<int,int>(50,350); Tuple <int,int>to = new Tuple<int,int>(50,650); Tuple from=新的Tuple(50350); Tuple to=新的Tuple(50650); 其中每个元组是一个坐标对。 我正在尝试使用元组创建多个坐标对的数组。有人能帮我一下吗 编辑:这是我迄今

我知道要在C#中创建元组,我们使用以下格式:

Tuple <int,int>from = new Tuple<int,int>(50,350);
Tuple <int,int>to = new Tuple<int,int>(50,650);
Tuple from=新的Tuple(50350);
Tuple to=新的Tuple(50650);
其中每个元组是一个坐标对。 我正在尝试使用元组创建多个坐标对的数组。有人能帮我一下吗

编辑:这是我迄今为止尝试过的。我只希望它是这种数组格式

 Tuple<int, int>[] coords = new Tuple<int,int>({50,350},{50,650},{450,650});
Tuple[]coords=新元组({50350},{50650},{450650});

编译器抱怨出了问题。。请告诉我它是什么?

您可以创建这样的数组。您将需要初始化每个对

Tuple<int, int>[] tupleArray = new Tuple<int, int>[10];

tupleArray[0] = new Tuple<int, int>(10,10);
Tuple[]tupleArray=新的Tuple[10];
tupleArray[0]=新的元组(10,10);

您可以如下定义它:

Tuple<int, int>[] tuples =
{
    Tuple.Create(50, 350),
    Tuple.Create(50, 650),
    ...
};

您可以使用

至于阵列:

Tuple<int,int>[] aaa = new {Tuple.Create(1, 1),Tuple.Create(1, 1)};
Tuple[]aaa=new{Tuple.Create(1,1),Tuple.Create(1,1)};
只需使用:

Tuple<int, int>[] tupleList =
{
    Tuple.Create(1, 2),
    Tuple.Create(2, 3)
};

如上所述,您打算使用
List
Dictionary
创建的符号创建
Tuple[]
,但不构建
Tuple[]
。编译器知道,您可以创建一个
KeyValuePair
数组或一个JSON数组,或者其他一些东西。在您的案例中,无法确定要创建的正确类型

您可以在创建值类型时不受影响,因为编译器可以识别它们并为您创建新对象。当你将对象传递进来时,你也可以不受影响,因为类型是可识别的。

在C#7中

对于命名版本,请执行以下操作:(谢谢)

所以我们可以用X,Y代替Item1,Item2

coords3.Select(t => $"Area = {t.X * t.Y}");
只有这个

(int x, int y)[] coords = new (int, int)[] {(1, 3), (5, 1), (8, 9)};

你可以使用一个列表。。。列表是一个通用集合。Tuple[]arrayOftuples=new Tuple[]{}如果只需要x和y坐标,为什么不使用
结构呢。关于元组的可读性,我至少会非常仔细地考虑。原因是我使用了一个内置函数,它接受元组数组作为参数。无法改变这一点:-/Downvoter,想发表评论吗?在这种情况下,处理元组似乎需要很多不必要的努力。这是C#7及更高版本的正确答案。如果您想要命名项,您也可以这样做:
var myTupleArray=new(double myFirstItem,int mySecondItem)[]={(12.0,2)、(13.0,3)、(14.0,4)}作为未来答案的提示-您将获得以下更好的投票:-1。响应的及时性(除非答案提供了新的内容)2。除了@DenisTsoi的评论之外(我同意),对答案的解释(提供描述可以让OP和读者理解为什么答案是值得的)。我还想指出,C#中的解构只能从C#7.0.Upvote中获得,用于现代元组。我希望有更多的人知道他们。是的,你必须有C#7.0,但现在很多人都有。不过,我同意你的答案中有更多实质性内容会有很大帮助。
var coords = new[] { ( 50, 350 ), ( 50, 650 ), ( 450, 650 )};
var coords2 = new(int X, int Y) [] { (50, 350), (50, 650), (450, 650) };
(int X, int Y) [] coords3 = new [] { (50, 350), (50, 650), (450, 650) };
coords3.Select(t => $"Area = {t.X * t.Y}");
(int x, int y)[] coords = new (int, int)[] {(1, 3), (5, 1), (8, 9)};