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: http://rextester.com/UIVZVX7918
public static List<ServiceEndPoint> GetServiceEndPoints()
{
const string source = "http://webSiteA.asmx,http://webSiteB.asmx";
const int instances = 3;
var splitEndPoints = source.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select((s, i) => new ServiceEndPoint
{
Index = i,
Uri = s
})
.ToList();
// Duplicate the contents of splitEndPoints "instances" number of times
var serviceEndPoints = new List<ServiceEndPoint>();
foreach (var point in splitEndPoints)
{
for (var i = 0; i < instances; i++)
{
serviceEndPoints.Add(point);
}
}
return serviceEndPoints;
}
public class ServiceEndPoint
{
public int Index { get; set; }
public string Uri { get; set; }
}
Is there a better way of doing it?
Python list can contain duplicate elements.
Method 1 – Using count() The code above uses a for loop to iterate each item in the list and count its appearance. If the value is a duplicate, it is added to the dup set. The output represents the duplicate items in the list.
All you need to know is that Set doesn't allow duplicates in Java. Which means if you have added an element into Set and trying to insert duplicate element again, it will not be allowed. In Java, you can use the HashSet class to solve this problem.
Perhaps something along the lines of:
var serviceEndPoints = splitEndPoints.SelectMany(t =>
Enumerable.Repeat(t, instances)).ToList();
That will give you "A,A,A,B,B,B,C,C,C". If you want "A,B,C,A,B,C,A,B,C":
var serviceEndPoints = Enumerable.Repeat(
splitEndPoints, instances).SelectMany(t => t).ToList();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With