[英]Quick way to create a list of values in C#?
我正在尋找一種在 C# 中創建值列表的快速方法。 在 Java 中,我經常使用下面的代碼片段:
List<String> l = Arrays.asList("test1","test2","test3");
除了下面明顯的一個之外,C# 中是否有任何等價物?
IList<string> l = new List<string>(new string[] {"test1","test2","test3"});
查看 C# 3.0 的集合初始值設定項。
var list = new List<string> { "test1", "test2", "test3" };
如果您想減少混亂,請考慮
var lst = new List<string> { "foo", "bar" };
這使用了 C# 3.0 的兩個特性:類型推斷( var
關鍵字)和列表的集合初始值設定項。
或者,如果您可以使用數組,則它甚至更短(少量):
var arr = new [] { "foo", "bar" };
在 C# 3 中,您可以執行以下操作:
IList<string> l = new List<string> { "test1", "test2", "test3" };
這使用了 C# 3 中新的集合初始值設定項語法。
在 C# 2 中,我只會使用您的第二個選項。
IList<string> list = new List<string> {"test1", "test2", "test3"}
您可以刪除new string[]
部分:
List<string> values = new List<string> { "one", "two", "three" };
你可以這樣做
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 });
正如您在大多數情況下所看到的,它只是在花括號中添加值,或者實例化一個新數組,然后是花括號和值。
您可以使用集合初始化程序在 C# 中稍微簡化該行代碼。
var lst = new List<string> {"test1","test2","test3"};
您可以創建輔助通用靜態方法來創建列表:
internal static class List
{
public static List<T> Of<T>(params T[] args)
{
return new List<T>(args);
}
}
然后用法非常緊湊:
List.Of("test1", "test2", "test3")
如果你想創建一個帶值的類型列表,這里是語法。
假設一類學生喜歡
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"}
};
你可以:
var list = new List<string> { "red", "green", "blue" };
或者
List<string> list = new List<string> { "red", "green", "blue" };
快速列出值? 甚至是對象列表!
我只是 C# 語言的初學者,但我喜歡使用
等等。
存儲物品的方法太多了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.