I have a method which should always return 5 Elements. Unfortunately, the input might be less than 5. How can I force Linq to always return 5 Elements?
e.g
public List<byte> GetFrob(List<int> maybeFrobs)
{
var result = maybeFrobs.Select(x => x.ToByte().ToList();
// can I extend the result to 5 elements, if less than 5?
return result;
}
>Solution :
You can generate a list of 5 "default" elements, then concat that to the end of your input collection.
IEnumerable<int> defaultElements = Enumerable.Repeat(0, 5);
List<byte> result = maybeFrobs
.Concat(defaultElements)
.Take(5)
.Select(x => x.ToByte())
.ToList();
By concating the collections then Takeing, you are guaranteed to have exactly 5 elements in by the time you hit Select.
Replace the 0 in Repeat with whatever you want the default element to be.