30% OFF - 10th Anniversary discount on new purchases until December 15 with code: ZZZANNIVERSARY10
C# Eval Expression LINQ Dynamic - Combine
LINQ Dynamic Combine Examples
C# Dynamic LINQ Combine examples using an Expression Evaluator.
Combine
This C# example uses the LINQ Combine method with a dynamic expression to calculate the dot product of two integer vectors. It uses a user-created sequence operator, Combine, to calculate the dot product, passing it a lambda function to multiply two arrays, element by element, and sum the result.
LINQ
int[] vectorA = {0, 2, 4, 5, 6}; int[] vectorB = {1, 3, 5, 7, 8}; var dotProduct = vectorA.Combine(vectorB, (a, b) => a * b).Sum(); Console.WriteLine("Dot product: {0}", dotProduct);
LINQ Execute
int[] vectorA = {0, 2, 4, 5, 6}; int[] vectorB = {1, 3, 5, 7, 8}; EvalManager.DefaultContext.RegisterExtensionMethod(typeof(CustomSequenceOperators)); var dotProduct = vectorA.Execute<int>("Combine(vectorB, (a, b) => a * b).Sum()", new {vectorB}); Console.WriteLine("Dot product: {0}", dotProduct);
Result
Dot product: 109