Marijke
Marijke

Reputation: 323

In Linq, is Single() after a Where clause useful?

There is something I don't really find an answer to:

db.Sensors.Where(s => s.Id == id).Single();

Is the Single() here necessary? There will normally only be given a single result, but is it really necessary to add it or is it redundant? What is the best practice?

Upvotes: 0

Views: 837

Answers (5)

Antoine V
Antoine V

Reputation: 7204

Yes. There is a light different.

The method Where returns an IEnumerable, means a list which contains zero or only objects which match your ID

The method Single returns a single object. But it throws an exception if there isn't an object or more than one object which matches your ID.

By your requirement, if you need a list to loop, use Where, if need to get an object, use Single

You chose your method

Upvotes: -1

JasperMoneyshot
JasperMoneyshot

Reputation: 357

It may not be necessary in your specific situation, but Single() enforces that there can only be one result and will throw an exception if there is more or less than one. In some situations where more or less than one result would highlight a bug then this can be useful.

From MSDN:

Single(IEnumerable)

Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.

Single(IEnumerable, Func)

Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.

Upvotes: 2

Trupti J
Trupti J

Reputation: 512

Use Single() when you feel it should explicitly always return 1 record. This will help you avoid logical errors.

If you are sure, db.Sensors.Where(s => s.Id == id) is going to return one and only one record, then Single() is not required.

Single() will throw an exception if db.Sensors.Where(s => s.Id == id) return null or more than one row. Single() will help you to know it is returning more than one row or null by throwing an exception.

Upvotes: 1

Milney
Milney

Reputation: 6417

Where returns an IEnumerable where as Single returns one object or throws an exception if there is 0 or more than one object, as other answers allude -

HOWEVER NOTE: This means it has to check ALL the objects, and therefore has a performance penalty - If you are confident there will only be one (i.e. there is a unique constraint on a database) then you can use First() instead, to get a single object and not bother checking all the others for duplicates.

Upvotes: 1

Mel Gerats
Mel Gerats

Reputation: 2252

You can combine them:

db.Sensors.Single(s => s.Id == id);

Upvotes: 4

Related Questions