创建N个对象并将其添加到列表中

Edm*_*g99 21 c# linq

我有一个方法,它接受N,我想要创建的对象的数量,我需要返回N个对象的列表.

目前我可以用一个简单的循环来做到这一点:

    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;
    }
Run Code Online (Sandbox Code Playgroud)

我想知道是否有另一种方式,也许用LINQ来创建这个列表.

我试过了:

    private static IEnumerable<MyObj> CreatePaxPriceTypes(int count, string foo)
    {
        var myList = new List<MyObj>(count);

        return myList.Select(x => x = new MyObj
            {
                bar = foo
            });

    }
Run Code Online (Sandbox Code Playgroud)

但这似乎填补了我的名单.

我尝试将选择更改为foreach但是同样的交易.

我意识到列表具有计数能力,LINQ没有找到任何要迭代的元素.

        myList.ForEach(x => x = new MyObj
        {
            bar = foo
        });
Run Code Online (Sandbox Code Playgroud)

是否有正确的LINQ运算符用于使其工作?或者我应该坚持循环?

Pat*_*iek 47

您可以使用它Range来创建序列:

return Enumerable.Range(0, count).Select(x => new MyObj { bar = foo });
Run Code Online (Sandbox Code Playgroud)

如果你想创建一个List,你必须这样ToList做.

请注意,它(可以说)是一个非显而易见的解决方案,所以不要抛弃创建列表的迭代方法.

  • 在这种情况下,它是“范围”还是“重复”都没有关系,因为您没有在“选择”中使用该对象。重要的是它会生成一个包含N个元素的序列,您需要精确地创建N个新对象... (2认同)

Mat*_*son 5

您可以创建通用的辅助方法,如下所示:

// Func<int, T>: The int parameter will be the index of each element being created.

public static IEnumerable<T> CreateSequence<T>(Func<int, T> elementCreator, int count)
{
    if (elementCreator == null)
        throw new ArgumentNullException("elementCreator");

    for (int i = 0; i < count; ++i)
        yield return (elementCreator(i));
}

public static IEnumerable<T> CreateSequence<T>(Func<T> elementCreator, int count)
{
    if (elementCreator == null)
        throw new ArgumentNullException("elementCreator");

    for (int i = 0; i < count; ++i)
        yield return (elementCreator());
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它们:

int count = 100;

var strList = CreateSequence(index => index.ToString(), count).ToList();

string foo = "foo";
var myList = CreateSequence(() => new MyObj{ Bar = foo }, count).ToList();
Run Code Online (Sandbox Code Playgroud)