Nikolay Nikolay - 4 months ago 22
C# Question

How I can understand when FirstOrDefault found nothing in sorted list?

I have

SortedList<DateTime, object>
. Each times in it is a
KeyValuePair<>
which is a struct. So, how can I understand when method
FirstOrDefault
found nothing in this list ?(for classes it returns
null
but for a
struct
?)

Why I just cant compare
default(KeyValuePair<Key, Value>)
and result of
FirstOrDefault
?

private SortedList<DateTime, GatewayPassage> gwPassages =
new SortedList<DateTime, GatewayPassage>(new DescDateTimeComparer());

var lastGwPassages = gwPassages.FirstOrDefault(x => x.Value.Tag == tag &&
x.Value.Gateway == gateway);


I want condition like "if found nothing"

if(lastGwPassages == %some kind of default value%)

Answer

Cast the items into a KeyValuePair<DateTime,object>? and then you will be able to check if it is equals to null.

SortedList<DateTime, object> collection = new SortedList<DateTime, object>()
{
    {  new DateTime(2016,1,2), new object() },
    {  new DateTime(2016,1,1), new object() },
    {  new DateTime(2016,1,3), new object() },
};

var firstOrDefault = collection.Cast<KeyValuePair<DateTime,object>?>().FirstOrDefault(); // date of 1/1/2016
var checkIfDefault = firstOrDefault == null; // false

collection.Clear();

firstOrDefault = collection.Cast<KeyValuePair<DateTime, object>?>().FirstOrDefault(); // null
checkIfDefault = firstOrDefault == null; // true

In your example code:

var lastGwPassages = gwPassages.Cast<KeyValuePair<DateTime,GatewayPassage>?>()
                               .FirstOrDefault(x => x.Value.Tag == tag &&
                                                    x.Value.Gateway == gateway);

Now you can do lastGwPassages == null

Comments