D
D
Dmitry Guketlev2011-01-20 19:17:34
C++ / C#
Dmitry Guketlev, 2011-01-20 19:17:34

Linq select first or null

Let's say there is some data sample. I need to make a request and find out if there is some element and get it if it exists.

Option 1: The problem is obvious: two queries will be executed. Option 2: Now there is no problem, one request. But somehow this fuss with List is annoying. Why not for example FirstOrNull? Of course, you can write your own extension method, but there must be a convenient mechanism? UPD: I sketched an extension method for myself. Tell me that I invented the wheel and how to do what I need?
object MyObject = null;
if(DataContext.SomeTable.Where(....).Any())
{
MyObject = DataContext.SomeTable.First(....);
}



object MyObject = null;
List<object> MyObjectList = DataContext.SomeTable.Where(....).Take(1).ToList();
if(MyObjectList.Any())
{
MyObject = MyObjectList.First();
}



/// <summary>
/// Возвращает первый подходящий элемент или null
/// </summary>
/// <typeparam name="T">Тип элемента</typeparam>
/// <param name="source">Источник для поиска</param>
/// <param name="predicate">Функция для фильтрации элементов в источнике</param>
/// <returns>Первый подходящий элемент или null</returns>
public static T FirstOrNull<T>(this IEnumerable<T> source, Func<T, bool> predicate = null) where T : class
{
List<T> lst = null;
if (predicate != null)
lst = source.ToList();
else
lst = source.Where(predicate).Take(1).ToList();
if (lst.Any())
return lst.First();
else
return null;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question