You could do something like:
var result = myList.Concat(Enumerable.Repeat(default(int), 20)).Take(20);
And it would be easy to turn this into an extension method:
public static IEnumerable<T> TakeOrDefault<T>(this IEnumerable<T> list, int count, T defaultValue)
{
return list.Concat(Enumerable.Repeat(defaultValue, count)).Take(count);
}
But there is a subtle gotcha here. This would work perfectly fine for value types, for a reference type, if your defaultValue
isn't null, you are adding the same object multiple times. Which probably isn't want you want. For example, if you had this:
var result = myList.TakeOrDefault(20, new Foo());
You are going to add the same instance of Foo
to pad your collection. To solve that problem, you'd need something like this:
public static IEnumerable<T> TakeOrDefault<T>(this IEnumerable<T> list, int count, Func<T> defaultFactory)
{
return list.Concat(Enumerable.Range(0, count).Select(i => defaultFactory())).Take(count);
}
Which you'd call like this:
var result = myList.TakeOrDefault(20, () => new Foo())
Of course, both methods can co-exist, so you could easily have:
// pad a list of ints with zeroes
var intResult = myIntList.TakeOrDefault(20, default(int));
// pad a list of objects with null
var objNullResult = myObjList.TakeOrDefault(20, (object)null);
// pad a list of Foo with new (separate) instances of Foo
var objPadNewResult = myFooList.TakeOrDefault(20, () => new Foo());
default(int)
is just a convoluted way of writing0
... – Revisedefault(string)
ordefault(DateTime)
. Just as importantly, you can usedefault(T)
with generics. – Masrystring
has plenty of simple literals, anddefault(DateTime)
is yet again just a less readable way of writingDateTime.MinValue
.default
only exists for generics, and there's no point in using it with a concrete type. – ReviseDateTime.MinValue
has an explicit meaning to me saying "this is the lowest possible value a datetime can have".default(DateTime)
says "this is the default value". There's no string literal fornull
.string.Empty
is an empty string (do you usestring.Empty
or""
?@""
?).default(string)
is anull
of typestring
- very important for type inference. What a feature was originally designed doesn't matter all that much - the important thing is what it's actually good at doing :) – Masry