2

I know this should be easy to do, but suppose, in my C# application, I have a IEnumerable<string> and I need to create a larger enumerable with nulls for the extra values.

So, simply for example's sake, suppose my enumerable has 12 elements and I need to create a final list of 24 elements (therefore the final 12 being nulls). I know I could program it using a for loop, but there has to be an easy way to do this using Linq and I'm just not sure which method to use.

Thanks!!

John Bustos
  • 19,036
  • 17
  • 89
  • 151

3 Answers3

3

I would suggest using Enumerable.Range or Repeat

var list = yourList.Concat(Enumerable.Range(1, 24).Select(i => null)).Take(24);

var list = yourList.Concat(Enumerable.Repeat(null, 24)).Take(24);
MikeT
  • 5,398
  • 3
  • 27
  • 43
  • Thanks so much!! - I **REALLY** like the `take(24)` idea! – John Bustos Mar 18 '16 at 14:26
  • 1
    @JohnBustos This is the safest as you don't run into exceptions if the original sequence has more than 24 items (also doesn't potentially iterate your original sequence twice). Only possible caveat is if it does have more than 24 this will truncate it, but that seems fairly reasonable. – juharr Mar 18 '16 at 14:33
  • I can see that... Truly the safest way. Thank you! – John Bustos Mar 18 '16 at 14:36
  • 1
    note that var list is actually an IEnumerable you need to call ToList to get an actual list out of it – MikeT Mar 18 '16 at 14:36
2

Repeat.

List<string> list = new List<string>() { "one", "two", "three" };
list.AddRange(Enumerable.Repeat((string)null, 10));

You can do this to get 24 elements.

list.AddRange(Enumerable.Repeat((string)null, 24-list.Count()));
Nikki9696
  • 6,260
  • 1
  • 28
  • 23
2

Here's the first thing that popped into my head:

currentList = currentList.Concat(                 // build onto your current list
    Enumerable.Range(1, 24 - currentList.Count()) // number of elements needed
    .Select(i => (string)null));                  // what you want the element to be
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • Thanks for the detailed explanation, @Cory, it's taking me a bit to wrap my head around, but it seems like the way you've broken it down, it would make a good pattern to know how to do it for any situation. thanks!!! – John Bustos Mar 18 '16 at 14:28