I very much like the sound of this ElementAtOrDefaultOperator for use with generic lists, but I cant figure out how to define a default type for my list of objects. From what I understand, the defaultvalue will be null if I have a list of objects as below, but I would like to return my own version of a default object with proper values. Here is what I mean:
ClassA {
string fieldA;
string fieldB;
ClassB fieldC;
//constructor
}
List<ClassA> myObjects = new List<ClassA>();
myObjects.Add( //new object )
myObjects.Add( //new object )
So I want to be able to do the following:
ClassA newObject = myObjects.ElementAtOrDefault(3);
And have newObject be a default type of ClassA that I define somewhere. I thought there might be a SetDefaultElement or some other method but I dont think it exists.
Any thoughts?
Just write your own extension method:
static T ElementAtOrDefault<T>(this IList<T> list, int index, T @default)
{
return index >= 0 && index < list.Count ? list[index] : @default;
}
and call:
var item = myObjects.ElementAtOrDefault(3, defaultItem);
Or if you want the default to be evaluated lazily, use a Func<T>
for the default:
static T ElementAtOrDefault<T>(this IList<T> list, int index,
Func<T> @default)
{
return index >= 0 && index < list.Count ? list[index] : @default();
}
This form, for example, would allow you to use a pre-defined item (the first, for example):
var item = myObjects.ElementAtOrDefault(3, myObjects.First);
or more flexibly:
var item = myObjects.ElementAtOrDefault(3, () => myObjects[2]);
or
var item = myObjects.ElementAtOrDefault(3, () => new MyObject {...});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With