Junior — Middle
How can the LastOrDefault method be implemented for a collection without knowing the element type in advance?
sobes.tech AI
Answer from AI
To implement the LastOrDefault method for a collection without knowing the element type in advance, you can use generics and LINQ in C#.
If the collection implements IEnumerable<T>, you can write a generic method:
public static T LastOrDefaultGeneric<T>(IEnumerable<T> source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
T last = default;
bool foundAny = false;
foreach (var item in source)
{
last = item;
foundAny = true;
}
return foundAny ? last : default;
}
This method iterates over all elements and returns the last one, or the default value if the collection is empty.
If the element type is unknown and the collection is non-generic (for example, IEnumerable), you can use object:
public static object LastOrDefaultNonGeneric(IEnumerable source)
{
if (source == null) throw new ArgumentNullException(nameof(source));
object last = null;
bool foundAny = false;
foreach (var item in source)
{
last = item;
foundAny = true;
}
return foundAny ? last : null;
}
Thus, you can get the last element without knowing the type in advance.