Very simple problem. I have a list of values which I want to pad out with empty values such that I always have X number of items returned.
List<int> list = new List<int>() { 10, 20, 30 };
IEnumerable<int> values = list
.OrderByDescending( i => i )
.Union( Enumerable.Repeat( 0 , 5 ) );
foreach (var item in values.Take(5))
Console.Write( item + " ");
I would expect an output like “30 20 10 0 0 ” But surprisingly I only get “30 20 10 0”.
foreach (var i in Enumerable.Repeat( 0, 5 ).Take(3))
Console.Write( i + " " );
This code will return “0 0 0 “. Likewise “list.Take(3)” returns “30 20 10 “.
The reason is that
Enumerable.Unionremoves duplicates. So you may want to useEnumerable.Concatinstead which dsoesn’t remove duplicates.Another option i would prefer is to use
Enumerable.ElementAtOrdefaultto select the elements from an index created byEnumerable.Rangewhere the second argument is the desired count: