在C#中创建值列表的快速方法?


106

我正在寻找一种在C#中创建值列表的快速方法。在Java中,我经常使用以下代码段:

List<String> l = Arrays.asList("test1","test2","test3");

除了下面明显的内容以外,C#中是否还有其他等效内容?

IList<string> l = new List<string>(new string[] {"test1","test2","test3"});

Answers:



19

如果您想减少混乱,请考虑

var lst = new List<string> { "foo", "bar" };

这使用了C#3.0的两个功能:类型推断(var关键字)和列表的集合初始值设定项。

或者,如果您可以使用数组,则它甚至会更短(少量):

var arr = new [] { "foo", "bar" };

2
我通常不会选择基于哪个数据结构来初始化的字符较少的数据结构...
Harrichael

1
@Harrichael对,我也不是。但是除非您需要列表,否则没有理由使用列表。
Konrad Rudolph'6

10

在C#3中,您可以执行以下操作:

IList<string> l = new List<string> { "test1", "test2", "test3" };

这将使用C#3中的新集合初始化器语法。

在C#2中,我只使用第二个选项。


Nitpick:集合初始化程序,而不是对象初始化程序。
Timwi'3


5

您可以删除该new string[]部分:

List<string> values = new List<string> { "one", "two", "three" };


3

你可以这样做

var list = new List<string>{ "foo", "bar" };

这是其他常见数据结构的其他一些常见实例:

字典

var dictionary = new Dictionary<string, string> 
{
    { "texas",   "TX" },
    { "utah",    "UT" },
    { "florida", "FL" }
};

数组列表

var array = new string[] { "foo", "bar" };

队列

var queque = new Queue<int>(new[] { 1, 2, 3 });

叠放

var queque = new Stack<int>(new[] { 1, 2, 3 });

如您所见,在大多数情况下,它只是在花括号中添加值,或者实例化一个新数组,后跟花括号和值。


1

您可以创建帮助程序的通用静态方法来创建列表:

internal static class List
{
    public static List<T> Of<T>(params T[] args)
    {
        return new List<T>(args);
    }
}

然后用法非常紧凑:

List.Of("test1", "test2", "test3")

1

如果要创建带有值的类型列表,请使用以下语法。

假设某类学生喜欢

public class Student {
   public int StudentID { get; set; }
   public string StudentName { get; set; }
 }   

您可以列出如下列表:

IList<Student> studentList = new List<Student>() { 
                new Student(){ StudentID=1, StudentName="Bill"},
                new Student(){ StudentID=2, StudentName="Steve"},
                new Student(){ StudentID=3, StudentName="Ram"},
                new Student(){ StudentID=1, StudentName="Moin"}
            };

-5

快速列出值?甚至是对象列表!

我只是C#语言的初学者,但我喜欢使用

  • 哈希表
  • 数组列表
  • 数据表
  • 数据集

等等

存储物品的方式太多了

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.