Nikolay Nikolay - 1 year ago 584
C# Question

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

I have

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

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

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 Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download