Linq to select the first or null

0 like 0 dislike
3 views
Let's have some sample data. I need to make a request and see if there's some element and get it if it exist.

Option 1:
object MyObject = null;
if(DataContext.SomeTable.Where(....).Any())
{
MyObject = DataContext.SomeTable.First(....);
}


obvious problem: the two request.

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

Now there is no problem, one request. But somehow this fuss with List annoying. Why not for example FirstOrNull? You can of course your method is the extension to write, but there must be a convenient mechanism?

UPD: sketched for method extension. Tell me I invented the Bicycle and how to do what I need?
///
/// Returns the first matching element or null
///

/// Item type
/// A source for finding
/// A function to filter items at the source
/// The first matching element or null
public static T FirstOrNull(this IEnumerable source, Func predicate = null) where T : class
{
List 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;
}
by | 3 views

1 Answer

0 like 0 dislike
.FirstOrDefault()?
by

Related questions

0 like 0 dislike
3 answers
asked Jun 14, 2019 by aleksey_semenov
0 like 0 dislike
1 answer
0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
asked May 2, 2019 by Jeer
0 like 0 dislike
2 answers
110,608 questions
257,186 answers
0 comments
28,875 users