Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linq: Get a List with a guaranteed length?

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;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading