开发者

Difference between Where and Single

I'm trying to figure out the d开发者_如何学Pythonifference between Where(Expression) and Single(Expression).

Is the Expression passed into single forwarded to a Where function?

eg, are these two statements the same?

var result = context.Persons.Single(p => p.ID == 5);
var result2 = context.Persons.Where(p => p.ID == 5).Single();


Single returns you a Person, whereas the Where will return you an IEnumerable<Person>.

Passing the where expression into the single is just syntactic sugar.

Both the lines are functionally equivalent. The first I imagine could be ever so marginally more efficient. It's also easier on the eye in my opinion.


There is another difference though. Single() will throw an exception if the predicate used returns more than one element. In case the filter, when applied on an enumerable returns only one element, it returns that element without throwing an exception.

int[] a = {1, 2, 3};
var odd_Nos = a.Single(num => num % 2 != 0) // will throw exception (an InvalidOperationException)
var even_Nos = a.Single(num => num % 2 == 0) // will not throw exception

If you want just the first to appear, you can use the First() or FirstOrDefault() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜