如何轻松地初始化元组的列表?初始化、轻松、列表

2023-09-07 11:53:14 作者:键盘上的眼泪

我爱元组。它们允许你快速组相关的信息一起,而无需编写一个结构或类吧。这是非常有用的,而重构非常局部化code。

初​​始化它们的列表但似乎有点多余了。

  VAR tupleList =新名单,其中元组LT; INT,字符串>>
{
    Tuple.Create(1,牛),
    Tuple.Create(5,鸡),
    Tuple.Create(1,飞机)
};
 

有没有更好的办法?我喜欢沿着字典初始化通过一项解决方案。

 词典< INT,字符串>学生=新字典< INT,字符串>()
{
    {111,的Bleh},
    {112,bloeh},
    {113,嗒嗒}
};
 

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

解决方案

是的! 这是可能的。

  

在集合初始化的的 {} 的语法适用于所有的的IEnumerable 的   类型,有一个的添加的方法,正确的参数量。   而没有如何工作在幕后,这意味着你可以   T>只是从列表&LT延长的,添加自定义添加的方法来初始化    T 的,和你做!

 公共类TupleList< T1,T2> :列表<元组LT; T1,T2>>
{
    公共无效添加(T1项目,T2 ITEM2)
    {
        加入(新行< T1,T2>(项目,ITEM2));
    }
}
 
Eclipse把工程初始化为本地库并推送远程库 重点

这可以让你做到以下几点:

  VAR groceryList =新TupleList< INT,字符串>
{
    {1,猕猴桃},
    {5,苹果},
    {3,土豆},
    {1,番茄}
};
 

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?

解决方案

Yes! This is possible.

The { } syntax of the collection initializer works on any IEnumerable type which has an Add method with the correct amount of arguments. Without bothering how that works under the covers, that means you can simply extend from List<T>, add a custom Add method to initialize your T, and you are done!

public class TupleList<T1, T2> : List<Tuple<T1, T2>>
{
    public void Add( T1 item, T2 item2 )
    {
        Add( new Tuple<T1, T2>( item, item2 ) );
    }
}

This allows you to do the following:

var groceryList = new TupleList<int, string>
{
    { 1, "kiwi" },
    { 5, "apples" },
    { 3, "potatoes" },
    { 1, "tomato" }
};