LINQ - Different syntax style, different result?

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

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 when a match cannot be found, and true for the last, and I cannot understand why this is happening.

I am new to LINQ, so I could have missed something really basic, but at the same time it made me crazy.

+8
c # linq
source share
2 answers

The second code returns an object that represents the query that you are calling; it will never be zero. Although once listed, this may be an empty collection. (still not null though)

First, you call FirstOrDefault, which forces a single result into a single variable, returning null if there are no results. If you did Where instead of FirstOrDefault , you would get the same result both times.

+10
source share

The first expression uses the Extension Method and the second uses the LINQ Query Expression .

In your first methods, FirstOrDefault returns the first element of a sequence or the default value if the sequence contains no elements. Here you are working on objects, so your default return is NULL if your result does not contain any element.

On the other hand, your second statement always returns the IEnumerable<T> value of the collection type, and it will never be null. you can simply check if the collection contains elements using the Collection Count property.

If you use the .Where() extension method in your first expression, then it will be equivalent to the second.

Check out these links for details and differences.

+1
source share

All Articles