public static IEnumerableTraverse (this T root, Func > getChildren) { return Enumerable.Repeat(root, 1) .Concat((getChildren(root) ?? Enumerable.Empty ()) .SelectMany(child => Traverse(child, getChildren))); }
Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts
Thursday, October 6, 2016
Generic extension method for traversing object graphs
Thursday, June 28, 2012
Calculate the exponential moving average of a stream of numbers
public static IEnumerable<double> ExponentialMovingAverage(this IEnumerable<double> source, double alpha) { double? last = null; return source.Select( value => { var average = last != null ? alpha*value + (1 - alpha)*last.Value : value; last = average; return average; }); }
Thursday, February 16, 2012
Create a fast compiled method invoker using LINQ
var method = new Func<double, double, double>(Math.Pow).Method; var parameter = Expression.Parameter(typeof(object[])); var args = method.GetParameters() .Select((param, i) => Expression.Convert( Expression.ArrayIndex(parameter, Expression.Constant(i)), param.ParameterType)); var expr = Expression.Lambda<Func<object[], object>>( Expression.Convert(Expression.Call(method, args), typeof(object)), parameter); var invoker = expr.Compile(); var result = invoker(new object[] {Math.PI, 2.0});
Saturday, December 17, 2011
Remove matching C# region directives using LINQ
var flag = false; var modified = false; var lines = File.ReadLines(fileName) .Where(line => { if ((!flag && line.Contains("#region " + regionName)) || (flag && line.Contains("#endregion"))) { flag = !flag; modified = true; return false; } return true; }) .ToArray(); if (modified) { File.WriteAllLines(fileName, lines); }
Subscribe to:
Posts (Atom)