Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Different syntax style, different result?

Tags:

c#

linq

Can someone tell me the difference the following two LINQ statements please?

var ChkUnique = DB.BusinessFile.FirstOrDefault(c => c.ROCNo == txtBoxID.Text);

and

var ChkUnique = from c in DB.BusinessFile 
                where c.ROCNo == (string)txtBoxID.Text 
                select c;

ChkUnique != null returns false for the top one when a match cannot be found and true for the latter and I can't figure out why this is happening.

I'm new to LINQ so I could have missed something really basic but its driving me nuts at the moment.

like image 635
Permas Avatar asked Dec 15 '11 04:12

Permas


1 Answers

The second code is returning an object that represents the query you are calling; it will never be null. Though once enumerated, it could be an empty collection. (still not null, though)

Your first is calling FirstOrDefault, which is forcing a single result into a single variable, returning null if there are no results. If you did Where instead of FirstOrDefault, you would have the same result both times.

like image 175
Andrew Barber Avatar answered Sep 28 '22 08:09

Andrew Barber