创建N个对象并将它们添加到列表中 [英] Creating N objects and adding them to a list
问题描述
我有一个方法,它接受N个对象(我要创建的对象数),并且需要返回N个对象的列表.
I have a method which takes in N, the number of objects I want to create, and I need to return a list of N objects.
目前,我可以通过一个简单的循环来做到这一点:
Currently I can do this with a simple loop:
private static IEnumerable<MyObj> Create(int count, string foo)
{
var myList = new List<MyObj>();
for (var i = 0; i < count; i++)
{
myList .Add(new MyObj
{
bar = foo
});
}
return myList;
}
我想知道是否还有另一种方法,也许可以使用LINQ来创建此列表.
And I'm wondering if there is another way, maybe with LINQ to create this list.
我尝试过:
private static IEnumerable<MyObj> CreatePaxPriceTypes(int count, string foo)
{
var myList = new List<MyObj>(count);
return myList.Select(x => x = new MyObj
{
bar = foo
});
}
但这似乎确实填充了我的列表.
But this does seem to populate my list.
我尝试将选择更改为foreach,但处理相同.
I tried changing the select to a foreach but its the same deal.
我意识到该列表具有容量个计数,而LINQ找不到要迭代的任何元素.
I realized that the list has the capacity of count and LINQ is not finding any elements to iterate.
myList.ForEach(x => x = new MyObj
{
bar = foo
});
是否有正确的LINQ运算符可用于使其正常工作?还是我应该坚持循环?
Is there a correct LINQ operator to use to get this to work? Or should I just stick with the loop?
推荐答案
您可以使用Range
创建序列:
return Enumerable.Range(0, count).Select(x => new MyObj { bar = foo });
如果要创建List
,则必须ToList
.
请记住,这(可以说)是一种非显而易见的解决方案,因此,请不要放弃创建列表的迭代方法.
Mind you though, it's (arguably) a non-obvious solution, so don't throw out the iterative way of creating the list just yet.
这篇关于创建N个对象并将它们添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!