Create duplicate items in a list

后端 未结 3 1732
再見小時候
再見小時候 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条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 16:40

    Splitting the two components...

    var parts = source.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
    
    var serviceEndPoints = (from i in Enumerable.Range(0, instances * parts.Length)
                            let j = i / instances
                            let part = parts[j]
                            select new ServiceEndPoint { Index = j, Uri = part }).ToList();
    

    or...

    var parts = source.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
    
    var serviceEndPoints2 = (from i in Enumerable.Range(0, parts.Length)
                            let part = parts[i]
                            from j in Enumerable.Range(0, instances)                            
                            select new ServiceEndPoint { Index = i, Uri = part }).ToList();
    

    It's very similar to two for one inside the other :-)

提交回复
热议问题