Return only one result from LINQ Query

You can do it in two ways, either use First or use Single.

First returns only first row, even there are multiple rows

Single expects only one row to be returned, and if there are multiple rows, it throws exception.

So, use Single if you are expecting only one row to be returned.

EX: var book= from book in store where (book.price > 100) select book).First();
Generally , the query returns all books having price greater than 100. but , as we are using  " .First() " only first book will be returned.

No comments:

Post a comment