Error
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.
  • JHTMLicon not supported. File not found.

func

Short-circuiting LINQ aggregate in C#
Thursday, 06 October 2011 03:25
An aggregate extension method that stops as soon as the accumulated result reaches some stop value. Useful for implementing the "are all satisifed" and "is any satisfied" scenarios when testing predicates.

See http://programmaticallyspeaking.com/?p=153 for more info.


using System;
using System.Collections.Generic;

namespace ProgrammaticallySpeaking {
public static class ShortCircuit {
public static TAccumulate AggregateUntil(this IEnumerable source, TAccumulate seed, TAccumulate stop, Func func) {
var result = seed;
foreach (var element in source) {
result = func(result, element);
if (result.Equals(stop))
break;
}
return result;
}
}
}


Validation of arguments should be added, of course...

Read more: http://feeds.dzone.com/~r/dzone/snippets/~3/ka732NXWwDk/13671

 


Taxonomy by Zaragoza Online