所以,这是我的问题,我有一个给定的对象,它是一个 IEnumerable,并且我已经保证该集合总是最多有 4 个元素。现在,出于一个不重要的原因,我希望能够以某种优雅的方式“强制”集合包含 4 个元素(如果它有任何更少)。
我已经做了一些研究,最有说服力的候选者是 Zip,但它会在到达最短集合结束后停止压缩。
有没有办法在不制作我自己的扩展方法的情况下做到这一点?为了更好地解释我自己:
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.
提前致谢!