Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ How to define a default type for use with ElementAtOrDefault Operator

Tags:

c#

list

linq

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?

like image 548
Alex Avatar asked Jan 29 '09 11:01

Alex


1 Answers

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 {...}); 
like image 111
Marc Gravell Avatar answered Sep 21 '22 13:09

Marc Gravell