如何轻松初始化元组列表? [英] How to easily initialize a list of Tuples?

查看:25
本文介绍了如何轻松初始化元组列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢元组.它们允许您快速将相关信息组合在一起,而无需为其编写结构或类.这在重构非常本地化的代码时非常有用.

I love tuples. They allow you to quickly group relevant information together without having to write a struct or class for it. This is very useful while refactoring very localized code.

但是初始化它们的列表似乎有点多余.

Initializing a list of them however seems a bit redundant.

var tupleList = new List<Tuple<int, string>>
{
    Tuple.Create( 1, "cow" ),
    Tuple.Create( 5, "chickens" ),
    Tuple.Create( 1, "airplane" )
};

没有更好的方法吗?我很喜欢字典初始值设定项的解决方案.>

Isn't there a better way? I would love a solution along the lines of the Dictionary initializer.

Dictionary<int, string> students = new Dictionary<int, string>()
{
    { 111, "bleh" },
    { 112, "bloeh" },
    { 113, "blah" }
};

我们不能使用类似的语法吗?

Can't we use a similar syntax?

推荐答案

c# 7.0 允许您这样做:

c# 7.0 lets you do this:

  var tupleList = new List<(int, string)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

如果你不需要List,而只需要一个数组,你可以这样做:

If you don't need a List, but just an array, you can do:

  var tupleList = new(int, string)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

如果你不喜欢Item1"和Item2",你可以这样做:

And if you don't like "Item1" and "Item2", you can do:

  var tupleList = new List<(int Index, string Name)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

或者对于数组:

  var tupleList = new (int Index, string Name)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

让你做:tupleList[0].IndextupleList[0].Name

框架 4.6.2 及以下

您必须安装 System.ValueTupleNuget 包管理器.

You must install System.ValueTuple from the Nuget Package Manager.

框架 4.7 及以上

它内置于框架中.不要不要安装System.ValueTuple.实际上,删除它从 bin 目录中删除它.

It is built into the framework. Do not install System.ValueTuple. In fact, remove it and delete it from the bin directory.

注意:在现实生活中,我无法在牛、鸡或飞机之间做出选择.我真的会很伤心.

这篇关于如何轻松初始化元组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆