You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
FirstOrNullable and similar method for struct collection #28650
publicstaticT?FirstOrNull<T>(thisIEnumerable<T>items)whereT:struct{}publicstaticT?LastOrNull<T>(thisIEnumerable<T>items)whereT:struct{}publicstaticT?ElementAtOrNull<T>(thisIEnumerable<T>items,intindex)whereT:struct{}// and so on
Reacted by bugproof, Pavel Anikhouski, Joseph Musser, Viacheslav Ivanov, Mrxx99, Angius, Tim van den Essen, Georg Jung, Amr, Nathan Povo and 13 more
FirstOrNull makes much more sense. 'Nullable' includes both null and values.
I have *OrNull extension methods that travel around with me for pretty much every *OrDefault BCL API, e.g. GetValueOrNull(TKey key) on IReadOnlyDictionary.
@dark2201 - I'm pretty sure the intent was that the behavior was the same.
Although it's true that adding an extra operator adds processing time, I'm not sure that a First case is going to really make a difference. Last, though, will need to convert everything before it can return any result.
While this would be awesome, I do think it should be broader than just structs. It is something that would be helpful for all value types. ints, bools, or even enums. 100% vote for this, but for all value types.
Would you be able to provide an example of how such a method would be used? Presumably the motivation is to work around the shortcomings of GetValueOrDefault() when used over value types? If that is the case, would the already approved overloads in #20064 not suffice to work around this problem?
From giving it a quick look (didn't read fully in-depth), I think so. The problem I came here and added my vote for was the use case mentioned in that thread... of needing to return a default value from an Enumberable of enums, but not being able to use FirstOrDefault, because "was it a valid value (0) or was it empty, and so it returned default (0)."
@eiriktsarpalis The OrDefault methods approved in #20064 can't cover this use case because they do not allow lazy evaluation to obtain the default value.
How would you implement the same thing with the proposal in #20064? Even if the OrDefault methods gained Func<T> defaultFactory methods, the syntax would involve unwieldly nesting (and avoidable allocations) rather than a linear pipeline.
Taking a look at how the Roslyn compiler codebase uses these extension methods might be useful.
With FirstOrDefault, you can't distinguish between there is zero existing in the list, or there is no number less than one
With 20064, you don't have ability to specify null as default for struct, or you need to cast number to be nullable
@jnm2 Noted. With the upcoming inclusion of discriminated unions in future versions of C#, I wouldn't be too surprised if we ended up adding a true option type. This would provide a solution that works for all types and not just structs.
Reacted by Joseph Musser and Juliano Leal Goncalves
As long as the syntax example above wouldn't become belabored, I like that concept a lot. The solution for non-nullable reference types in that example is of course to swap FirstOrNull with FirstOrDefault, but there is no nice solution for nullable reference types without an option type.
// besides having to cast everything to Nullable, I have to use ! and .Value inside the predicate, unnecessarily... :(varuf=addressComponents.EnumerateArray().Cast<JsonElement?>().FirstOrDefault(a =>a!.Value.GetProperty("types").EnumerateArray().Select(t =>t.GetString()).Contains(address_type_1))?.GetProperty("short_name").GetString();// OR// without the cast to JsonElement?, I'm unable to use the safe navigation operatorvaraddressType1Value=addressComponents.EnumerateArray().FirstOrDefault(a =>a!.Value.GetProperty("types").EnumerateArray().Select(t =>t.GetString()).Contains(address_type_1));stringuf=null;if(addressType1Value.ValueKind!=JsonValueKind.Undefined){uf=addressType1Value.GetProperty("short_name").GetString();}
With the proposed API:
// no unnecessary casting, no ! and .Value cluttervaruf=addressComponents.EnumerateArray().FirstOrNull(a =>a.GetProperty("types").EnumerateArray().Select(t =>t.GetString()).Contains(address_type_1))?.GetProperty("short_name").GetString();
Activity
Grauenwolf commentedon Feb 8, 2019
I assume that this would be equivalent to
var x = list.Cast<int?>().FirstOrDefault();I think that
FirstOrNullis a better name.Thaina commentedon Feb 8, 2019
@Grauenwolf Not sure but I think implementation is even easier than that
I don't have naming preference just only want this functionality
jnm2 commentedon Feb 8, 2019
FirstOrNull makes much more sense. 'Nullable' includes both
nulland values.I have
*OrNullextension methods that travel around with me for pretty much every*OrDefaultBCL API, e.g.GetValueOrNull(TKey key)on IReadOnlyDictionary.bugproof commentedon Mar 21, 2019
@Grauenwolf no it would be faster,
Cast<T?>is slow. I vote forFirstOrNull,LastOrNulletc.Clockwork-Muse commentedon Mar 22, 2019
@dark2201 - I'm pretty sure the intent was that the behavior was the same.
Although it's true that adding an extra operator adds processing time, I'm not sure that a
Firstcase is going to really make a difference.Last, though, will need to convert everything before it can return any result.eidylon commentedon Aug 12, 2020
While this would be awesome, I do think it should be broader than just structs. It is something that would be helpful for all value types. ints, bools, or even enums. 100% vote for this, but for all value types.
Grauenwolf commentedon Aug 12, 2020
An int or boolean is a struct in .NET. You're probably thinking of C.
eidylon commentedon Aug 14, 2020
Huh. Did not realize that. Yup... learn something new every day. Okay then, I guess my comment is extraneous. 👍🏼👍🏼
eiriktsarpalis commentedon Nov 23, 2020
Would you be able to provide an example of how such a method would be used? Presumably the motivation is to work around the shortcomings of
GetValueOrDefault()when used over value types? If that is the case, would the already approved overloads in #20064 not suffice to work around this problem?eidylon commentedon Nov 23, 2020
From giving it a quick look (didn't read fully in-depth), I think so. The problem I came here and added my vote for was the use case mentioned in that thread... of needing to return a default value from an Enumberable of enums, but not being able to use FirstOrDefault, because "was it a valid value (0) or was it empty, and so it returned default (0)."
jnm2 commentedon Nov 23, 2020
@eiriktsarpalis The OrDefault methods approved in #20064 can't cover this use case because they do not allow lazy evaluation to obtain the default value.
With FirstOrNull:
How would you implement the same thing with the proposal in #20064? Even if the OrDefault methods gained
Func<T> defaultFactorymethods, the syntax would involve unwieldly nesting (and avoidable allocations) rather than a linear pipeline.Taking a look at how the Roslyn compiler codebase uses these extension methods might be useful.
Thaina commentedon Nov 23, 2020
@eiriktsarpalis
With
FirstOrDefault, you can't distinguish between there is zero existing in the list, or there is no number less than oneWith 20064, you don't have ability to specify
nullas default for struct, or you need to cast number to be nullableeiriktsarpalis commentedon Nov 23, 2020
@jnm2 Noted. With the upcoming inclusion of discriminated unions in future versions of C#, I wouldn't be too surprised if we ended up adding a true option type. This would provide a solution that works for all types and not just structs.
jnm2 commentedon Nov 23, 2020
As long as the syntax example above wouldn't become belabored, I like that concept a lot. The solution for non-nullable reference types in that example is of course to swap
FirstOrNullwithFirstOrDefault, but there is no nice solution for nullable reference types without an option type.artdedeco commentedon Aug 12, 2024
I just stumbled upon a use case for this:
Current alternatives:
With the proposed API:
Thaina commentedon Aug 13, 2024
@eiriktsarpalis Completed? Which version?
eiriktsarpalis commentedon Aug 13, 2024
I have no idea how this happened. This hasn't been addressed obviously.
s97712 commentedon May 30, 2025
Having trouble?
s97712 commentedon May 30, 2025
Has anyone followed up on this?
s97712 commentedon May 30, 2025
I'm fed up with the utterly baffling design of OrDefault.