Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

c# - Creating N objects and adding them to a list

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;
    }

And I'm wondering if there is another way, maybe with LINQ to create this list.

I've tried:

    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.

I tried changing the select to a foreach but its the same deal.

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
        });

Is there a correct LINQ operator to use to get this to work? Or should I just stick with the loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the Range to create a sequence:

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

If you want to create a List, you'd have to ToList it.

Mind you though, it's (arguably) a non-obvious solution, so don't throw out the iterative way of creating the list just yet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...