Creating N objects and adding them to a list

前端 未结 3 1340
盖世英雄少女心
盖世英雄少女心 2020-12-10 23:58

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:

相关标签:
3条回答
  • 2020-12-11 00:41

    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.

    0 讨论(0)
  • 2020-12-11 00:47

    You can Use Enumerable.Repeat

    IEnumerable<MyObject> listOfMyObjetcs = Enumerable.Repeat(CreateMyObject, numberOfObjects);
    

    For more info read https://msdn.microsoft.com/en-us/library/bb348899(v=vs.110).aspx

    0 讨论(0)
  • 2020-12-11 00:54

    You could create generic helper methods, like so:

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

    Then you could use them like this:

    int count = 100;
    
    var strList = CreateSequence(index => index.ToString(), count).ToList();
    
    string foo = "foo";
    var myList = CreateSequence(() => new MyObj{ Bar = foo }, count).ToList();
    
    0 讨论(0)
提交回复
热议问题