c# - Does a code that combines single() with yield make any sense? -
i came across code should return single object expected in list, code has iterator block yields found items, have simplified case in following example:
private static void methode_a() { console.write("{0} ", numberlist(2, 8).single()); } private static ienumerable<int> numberlist(int min, int max) { while (min < max) yield return min++; }
does make sense or there known benefits of combining single()
yield
on building list , asserting contains 1 single element?
the way works following:
- you call
numberlist(2, 8).single()
- the execution flow enters
while
loop first time , returns first result (2). - the execution flow continues on second iteration of loop , returns second element (3)
- the
.single
method throws exception , stops execution because expected there 1 element contained in enumerator
on other hand if call numberlist(2, 8).first()
here's happen:
- the execution flow enters
while
loop first time , returns first result (2). - the execution flow no longer continues in
while
loop because 1 element returned , element result of call
Comments
Post a Comment