I can do the following:
container.Users.Where(u => u.Name == "Omar").FirstOrDefault()
but
container.Users.FirstOrDefault(u => u.Name == "Omar")
returns a NotSupportedException (The method 'FirstOrDefault' is not supported.)
.
Since these are essentially the same, why is it no supported?
Use the FirstorDefault() method to return the first element of a sequence or a default value if element isn't there. List<double> val = new List<double> { }; Now, we cannot display the first element, since it is an empty collection.
The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource) , use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method as described in the Example section.
Remarks. The First<TSource>(IEnumerable<TSource>) method throws an exception if source contains no elements. To instead return a default value when the source sequence is empty, use the FirstOrDefault method.
The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data. First() will throw an exception if there is no result data, as you can see below.
The LINQ Translation engine used by the OData provider doesn't handle every scenario.
While these are logically the same, the expression for each must be generated to build the query string. The engine doesn't support the second form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With