快捷方式在C#创建单个项目列表 [英] Shortcut for creating single item list in C#

查看:116
本文介绍了快捷方式在C#创建单个项目列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,有一个内嵌的快捷方式来实例化一个List< T>与只有一个项目



目前,我正在做的:

 新的List<串>(新的String [] {称号}))

有了这个代码随处可见降低了可读性。我想用一个实用方法是这样的:

 公共静态列表< T> SingleItemList< T>(T值)
{
收益(新的List< T>(新T [] {}值));
}



所以,我可以做的:

  SingleItemList(标题); 

有一个较短/更清洁的方式?



< 。p>感谢


解决方案

只需使用这样的:

 列表与LT;字符串>名单=新名单,LT;串>(){单值}; 

您甚至可以省略()括号:

 列表<串GT;名单=新名单,LT;字符串> {单值}; 



更新:当然,这也适用于多个条目:

 列表<串GT;名单=新名单,LT;字符串> {值1,值2,...}; 


In C#, is there an inline shortcut to instantiate a List<T> with only one item.

I'm currently doing:

new List<string>( new string[] { "title" } ))

Having this code everywhere reduces readability. I've thought of using a utility method like this:

public static List<T> SingleItemList<T>( T value )
{
    return (new List<T>( new T[] { value } ));
}

So I could do:

SingleItemList("title");

Is there a shorter / cleaner way?

Thanks.

解决方案

Simply use this:

List<string> list = new List<string>() { "single value" };

You can even omit the () braces:

List<string> list = new List<string> { "single value" };

Update: of course this also works for more than one entry:

List<string> list = new List<string> { "value1", "value2", ... };

这篇关于快捷方式在C#创建单个项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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