C# 使用单个对象和另一个对象列表初始化列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13256787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize list with both a single object and another list of objects
提问by Joe W
I want to initialize a list with an object and a list of objects in that specific order. Currently, I am doing:
我想用一个对象和一个按特定顺序排列的对象列表来初始化一个列表。目前,我正在做:
List<MyObject> list = new List<MyObject>();
list.Add(object1); // object1 is type MyObject
list.AddRange(listOfObjects); // listOfObjects is type List<MyObject>
I was hoping to consolidate that into an initialization statement (the syntax is wrong of course):
我希望将其合并为一个初始化语句(当然语法是错误的):
List<MyObject> newList = new List<MyObject>() { object1, listOfObjects };
Is there a way to do this concisely?
有没有办法简洁地做到这一点?
采纳答案by Reed Copsey
If the order of the elements is not important, you can use:
如果元素的顺序不重要,您可以使用:
List<MyObject> newList = new List<MyObject>(listOfObjects) { object1 };
This works by using the List<T>constructor which accepts an IEnumerable<T>, then the collection initializer to add the other items. For example, the following:
这通过使用List<T>接受 an的构造函数IEnumerable<T>,然后使用集合初始值设定项来添加其他项来工作。例如,以下内容:
static void Main()
{
int test = 2;
List<int> test2 = new List<int>() { 3, 4, 5 };
List<int> test3 = new List<int>(test2) { test };
foreach (var t in test3) Console.WriteLine(t);
Console.ReadKey();
}
Will print:
将打印:
3
4
5
2
Note that the order is different than your original, however, as the individual item is added last.
请注意,订单与原始订单不同,因为单个项目是最后添加的。
If the order is important, however, I would personally just build the list, placing in your first object in the initializer, and calling AddRange:
但是,如果顺序很重要,我个人只会构建列表,将您的第一个对象放入初始化程序中,然后调用AddRange:
List<MyObject> newList = new List<MyObject> { object1 };
newList.AddRange(listOfObjects);
This makes the intention very clear, and avoids construction of temporary items (which would be required using LINQ's Concat, etc).
这使得意图非常明确,并避免了临时项目的构建(使用 LINQ 的 Concat 等需要这样做)。
回答by Lee
I think the best you can do is:
我认为你能做的最好的是:
List<MyObject> newList = new[] { object1 }.Concat(listOfObjects).ToList();

