C# Eval Expression LINQ Dynamic - First

LINQ Dynamic First Examples

C# Dynamic LINQ First examples using an Expression Evaluator.

First - Simple

This C# example uses the LINQ First method with a dynamic expression to find the first matching element as a Product, instead of as a sequence containing a Product.

LINQ

var products =getList();

var product = products.Where(p => p.ProductID == 12).First();

Console.WriteLine("ProductID : " + product.ProductID+ " ,ProductName : " + product.ProductName+ " ,Category : "+ product.Category+ " ,UnitPrice : "+ product.UnitPrice+" ,UnitsInStock : "+ product.UnitsInStock);

Try it online

LINQ Execute

var products =getList();

var product = products.Where(p => p.ProductID == 12).Execute<Product>("First()");

Console.WriteLine("ProductID : " + product.ProductID+ " ,ProductName : " + product.ProductName+ " ,Category : "+ product.Category+ " ,UnitPrice : "+ product.UnitPrice+" ,UnitsInStock : "+ product.UnitsInStock);

Try it online

Result

ProductID=12 ProductName=Queso Manchego La Pastora Category=Dairy Products UnitPrice=38.0000 UnitsInStock=86

First - Condition

This C# example uses the LINQ First method with a dynamic expression to find the first element in the array that starts with 'o'.

LINQ

private void uiFirst_Condition_LINQ_Click(object sender, EventArgs e)
string[] strings = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

var startsWithO = strings.First(s => s[0] == 'o');

Console.WriteLine("A string starting with 'o': {0}", startsWithO);

Try it online

LINQ Dynamic

string[] strings = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

var startsWithO = strings.First(s => "s[0] == 'o'");

Console.WriteLine("A string starting with 'o': {0}", startsWithO);

Try it online

LINQ Execute

string[] strings = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

var startsWithO =  strings.Execute<string>("First(s => s[0] == 'o')");

Console.WriteLine("A string starting with 'o': {0}", startsWithO);

Try it online

Result

A string starting with 'o': one


Contents