Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...