Default Value of a dictionary and FirstOrDefault() in LINQ mismatch
Why default value of a dictionary class is not same as default value returned by FirstOrDefault using LINQ?
Dictionary<Mode, string> myDict = new Dictionary<Mode, string>() { { Mode.First, "ValueFirst" }, { Mode.Second, "ValueSecond" }, { Mode.Third, "ValueThird" }, { Mode.Forth, "ValueForth" } };
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
var r2 = default(Dictionary<Mode, string>);
Here Mode is an enum. As a result, r1 is a key-value pair with default values, but r2 is null. Why?
c# linq default-value
|
show 1 more comment
Why default value of a dictionary class is not same as default value returned by FirstOrDefault using LINQ?
Dictionary<Mode, string> myDict = new Dictionary<Mode, string>() { { Mode.First, "ValueFirst" }, { Mode.Second, "ValueSecond" }, { Mode.Third, "ValueThird" }, { Mode.Forth, "ValueForth" } };
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
var r2 = default(Dictionary<Mode, string>);
Here Mode is an enum. As a result, r1 is a key-value pair with default values, but r2 is null. Why?
c# linq default-value
2
BecauseFirstOrDefault()
returns aKeyValuePair
. Not a dictionary.
– Gert Arnold
Nov 20 '18 at 22:40
Or, it can returndefault(KeyValuePair)
, which is null - always watch out for nulls onFirstOrDefault()
. That's related to your second question (aboutr2
). If you are working with a reference type (like aDictionary
), thendefault(YourReferenceTypeGoesHere)
is null - it's always null. If you usedefault
on a value type, then it's the zero-ish value, but for reference types, it's alwaysnull
– Flydog57
Nov 20 '18 at 22:44
1
KeyValuePair<,>
is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.
– Xiaoy312
Nov 20 '18 at 22:47
@Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.
– Flydog57
Nov 20 '18 at 22:48
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must useContainsKey
orTryGetValue
. Or use (worse)var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault();
so you can getnull
(which clearly means 'it wasn't there').
– mjwills
Nov 20 '18 at 23:02
|
show 1 more comment
Why default value of a dictionary class is not same as default value returned by FirstOrDefault using LINQ?
Dictionary<Mode, string> myDict = new Dictionary<Mode, string>() { { Mode.First, "ValueFirst" }, { Mode.Second, "ValueSecond" }, { Mode.Third, "ValueThird" }, { Mode.Forth, "ValueForth" } };
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
var r2 = default(Dictionary<Mode, string>);
Here Mode is an enum. As a result, r1 is a key-value pair with default values, but r2 is null. Why?
c# linq default-value
Why default value of a dictionary class is not same as default value returned by FirstOrDefault using LINQ?
Dictionary<Mode, string> myDict = new Dictionary<Mode, string>() { { Mode.First, "ValueFirst" }, { Mode.Second, "ValueSecond" }, { Mode.Third, "ValueThird" }, { Mode.Forth, "ValueForth" } };
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
var r2 = default(Dictionary<Mode, string>);
Here Mode is an enum. As a result, r1 is a key-value pair with default values, but r2 is null. Why?
c# linq default-value
c# linq default-value
edited Nov 21 '18 at 0:47
Mayank Garg
asked Nov 20 '18 at 22:36
Mayank GargMayank Garg
63
63
2
BecauseFirstOrDefault()
returns aKeyValuePair
. Not a dictionary.
– Gert Arnold
Nov 20 '18 at 22:40
Or, it can returndefault(KeyValuePair)
, which is null - always watch out for nulls onFirstOrDefault()
. That's related to your second question (aboutr2
). If you are working with a reference type (like aDictionary
), thendefault(YourReferenceTypeGoesHere)
is null - it's always null. If you usedefault
on a value type, then it's the zero-ish value, but for reference types, it's alwaysnull
– Flydog57
Nov 20 '18 at 22:44
1
KeyValuePair<,>
is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.
– Xiaoy312
Nov 20 '18 at 22:47
@Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.
– Flydog57
Nov 20 '18 at 22:48
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must useContainsKey
orTryGetValue
. Or use (worse)var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault();
so you can getnull
(which clearly means 'it wasn't there').
– mjwills
Nov 20 '18 at 23:02
|
show 1 more comment
2
BecauseFirstOrDefault()
returns aKeyValuePair
. Not a dictionary.
– Gert Arnold
Nov 20 '18 at 22:40
Or, it can returndefault(KeyValuePair)
, which is null - always watch out for nulls onFirstOrDefault()
. That's related to your second question (aboutr2
). If you are working with a reference type (like aDictionary
), thendefault(YourReferenceTypeGoesHere)
is null - it's always null. If you usedefault
on a value type, then it's the zero-ish value, but for reference types, it's alwaysnull
– Flydog57
Nov 20 '18 at 22:44
1
KeyValuePair<,>
is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.
– Xiaoy312
Nov 20 '18 at 22:47
@Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.
– Flydog57
Nov 20 '18 at 22:48
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must useContainsKey
orTryGetValue
. Or use (worse)var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault();
so you can getnull
(which clearly means 'it wasn't there').
– mjwills
Nov 20 '18 at 23:02
2
2
Because
FirstOrDefault()
returns a KeyValuePair
. Not a dictionary.– Gert Arnold
Nov 20 '18 at 22:40
Because
FirstOrDefault()
returns a KeyValuePair
. Not a dictionary.– Gert Arnold
Nov 20 '18 at 22:40
Or, it can return
default(KeyValuePair)
, which is null - always watch out for nulls on FirstOrDefault()
. That's related to your second question (about r2
). If you are working with a reference type (like a Dictionary
), then default(YourReferenceTypeGoesHere)
is null - it's always null. If you use default
on a value type, then it's the zero-ish value, but for reference types, it's always null
– Flydog57
Nov 20 '18 at 22:44
Or, it can return
default(KeyValuePair)
, which is null - always watch out for nulls on FirstOrDefault()
. That's related to your second question (about r2
). If you are working with a reference type (like a Dictionary
), then default(YourReferenceTypeGoesHere)
is null - it's always null. If you use default
on a value type, then it's the zero-ish value, but for reference types, it's always null
– Flydog57
Nov 20 '18 at 22:44
1
1
KeyValuePair<,>
is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.– Xiaoy312
Nov 20 '18 at 22:47
KeyValuePair<,>
is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.– Xiaoy312
Nov 20 '18 at 22:47
@Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.
– Flydog57
Nov 20 '18 at 22:48
@Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.
– Flydog57
Nov 20 '18 at 22:48
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must use ContainsKey
or TryGetValue
. Or use (worse) var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault();
so you can get null
(which clearly means 'it wasn't there').– mjwills
Nov 20 '18 at 23:02
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must use ContainsKey
or TryGetValue
. Or use (worse) var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault();
so you can get null
(which clearly means 'it wasn't there').– mjwills
Nov 20 '18 at 23:02
|
show 1 more comment
1 Answer
1
active
oldest
votes
Use default(KeyValuePair<,>)
to check for default value:
var kvp = dict.FirstOrDefault(...);
if (default(KeyValuePair<Mode, string>).Equals(kvp))
Alternatively, you could use an extension method here:
public static class KeyValuePairExtensions
{
public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
}
// usage
var kvp = dict.FirstOrDefault(...);
if (kvp.IsDefault())
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402621%2fdefault-value-of-a-dictionary-and-firstordefault-in-linq-mismatch%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Use default(KeyValuePair<,>)
to check for default value:
var kvp = dict.FirstOrDefault(...);
if (default(KeyValuePair<Mode, string>).Equals(kvp))
Alternatively, you could use an extension method here:
public static class KeyValuePairExtensions
{
public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
}
// usage
var kvp = dict.FirstOrDefault(...);
if (kvp.IsDefault())
add a comment |
Use default(KeyValuePair<,>)
to check for default value:
var kvp = dict.FirstOrDefault(...);
if (default(KeyValuePair<Mode, string>).Equals(kvp))
Alternatively, you could use an extension method here:
public static class KeyValuePairExtensions
{
public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
}
// usage
var kvp = dict.FirstOrDefault(...);
if (kvp.IsDefault())
add a comment |
Use default(KeyValuePair<,>)
to check for default value:
var kvp = dict.FirstOrDefault(...);
if (default(KeyValuePair<Mode, string>).Equals(kvp))
Alternatively, you could use an extension method here:
public static class KeyValuePairExtensions
{
public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
}
// usage
var kvp = dict.FirstOrDefault(...);
if (kvp.IsDefault())
Use default(KeyValuePair<,>)
to check for default value:
var kvp = dict.FirstOrDefault(...);
if (default(KeyValuePair<Mode, string>).Equals(kvp))
Alternatively, you could use an extension method here:
public static class KeyValuePairExtensions
{
public static bool IsDefault<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp) => default(KeyValuePair<Mode, string>).Equals(kvp);
}
// usage
var kvp = dict.FirstOrDefault(...);
if (kvp.IsDefault())
answered Nov 20 '18 at 22:53
Xiaoy312Xiaoy312
11.2k12133
11.2k12133
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402621%2fdefault-value-of-a-dictionary-and-firstordefault-in-linq-mismatch%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Because
FirstOrDefault()
returns aKeyValuePair
. Not a dictionary.– Gert Arnold
Nov 20 '18 at 22:40
Or, it can return
default(KeyValuePair)
, which is null - always watch out for nulls onFirstOrDefault()
. That's related to your second question (aboutr2
). If you are working with a reference type (like aDictionary
), thendefault(YourReferenceTypeGoesHere)
is null - it's always null. If you usedefault
on a value type, then it's the zero-ish value, but for reference types, it's alwaysnull
– Flydog57
Nov 20 '18 at 22:44
1
KeyValuePair<,>
is a struct, it can never be null. Unless we are talking about Nullable<KeyValuePair<,>>` which is another type.– Xiaoy312
Nov 20 '18 at 22:47
@Xiaoy312: Ooops! Didn't look it up. Makes sense for it to be a value type. Thanks! I've spent a lot of time over the past year cleaning up messes where co-workers called Whatever().FirstOrDefault() and then used the results without a null-check. It's one of my go to code review issues now.
– Flydog57
Nov 20 '18 at 22:48
var r1 = myDict.Where(d => d.Value == "Do not exist").FirstOrDefault();
This is a terrible idea. You can't distinguish whether there was really an entry there or not. If you want to know whether an entry was there you must useContainsKey
orTryGetValue
. Or use (worse)var r1 = myDict.Where(d => d.Value == "Do not exist").Cast<KeyValuePair<Mode, string>?>.FirstOrDefault();
so you can getnull
(which clearly means 'it wasn't there').– mjwills
Nov 20 '18 at 23:02