So, here is my issue, I have a given object which is an IEnumerable and I have been guaranteed that said collection will always have at most 4 elements. Now, for a reason that is not important, I’d like to be able to, in some elegant way, “force” the collection to contain 4 elements if it has any less.
I’ve already done some research and the most convincig candidate is Zip, but it stops zipping after it reaches the shortest collection’s end.
Is there any way of doing this without making my own extension method?
To better explain myself:
var list1 = new List<Dog> {
new Dog { Name = "Puppy" }
}
var list2 = new List<Dog> {
new Dog { Name = "Puppy1" },
new Dog { Name = "Puppy2" },
new Dog { Name = "Puppy3" },
new Dog { Name = "Puppy4" },
}
var other1 = list1.ExtendToNElements(4).ToList();
//Now other1's first element is an instance of Dog with Name = "Puppy"
//And the following 3 elements are null, or have a Dog with no name
//I don't really care about that
var other2 = list2.ExtendToNElements(4).ToList();
//other2 is the same as list2, nothing got added.
Thanks in advance!
Quick one-liner (which should count as “doable without an extension method”):
Since
Repeattakes an explicit count, passing inngives a reasonable upper bound. The elements are generated on-demand anyway. Usingsource.Count()would force execution ofsourcewhich isn’t ideal.Slightly more overengineered and flexible version: