tags:

views:

593

answers:

2

Hi there,

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?

+8  A: 

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 {...});
Marc Gravell
An appropriate overload could return default(T) as in the LINQ implementation.
sixlettervariables
@sixlettervariables - but that already exists in the non-overloaded, standard LINQ operator...
Marc Gravell
A: 

Fabulous. I thought this could have been achieved by writing a generic method but I figured it would have already been implemented.

Alex