Create duplicate items in a list

后端 未结 3 1722
再見小時候
再見小時候 2021-01-05 16:08

I have the following code to duplicate the members of a list X times.

Although it works it doesn\'t feel particularly clean.

Live code example:

3条回答
  •  旧时难觅i
    2021-01-05 16:44

    You can do this with a little Linq:

    int instances = 3;
    var serviceEndPoints = 
        (from e in Enumerable.Range(0, instances)
         from x in serviceEndPoints
         select x)
        .ToList();
    

    Or if you prefer fluent syntax:

    var serviceEndPoints = Enumerable
        .Range(0, instances)
        .SelectMany(e => serviceEndPoints)
        .ToList();
    

    Note that given a list like { A, B, C } will produce a list like { A, B, C, A, B, C, A, B, C }. If you want to produce a list like { A, A, A, B, B, B, C, C, C }, you can simply reverse the order of the collections:

    var serviceEndPoints = 
        (from x in serviceEndPoints
         from e in Enumerable.Range(0, instances)
         select x)
        .ToList();
    

    Or in fluent syntax:

    var serviceEndPoints = serviceEndPoints
        .SelectMany(x => Enumerable.Range(0, instances), (x, e) => x)
        .ToList();
    

提交回复
热议问题