gpt4 book ai didi

c# - 如何动态创建 lambda 表达式

转载 作者:太空狗 更新时间:2023-10-29 19:46:49 27 4
gpt4 key购买 nike

假设我有以下类(class):

public class Show
{
public string Language { get; set; }
public string Name { get; set; }
}

基于这些信息,我的目标是创建一个像这样的 lambda 表达式:

g => g.Language == lang && g.Name == name

langname是我想在创建表达式时添加为常量值的局部变量。

如您所见,编译函数的类型为 Func<Genre, bool>

为了帮助大家更清楚的理解,我想实现类似这样的东西:

string lang = "en";
string name = "comedy";
Genre genre = new Genre { Language = "en", Name = "comedy" };
Expression<Func<Genre, bool>> expression = CreateExpression(genre, lang, name);
// expression = (g => g.Language == "en" && g.Name == "comedy")

我知道表达式树的存在,但我对这个主题还很陌生,所以我什至不知道如何开始。

这个问题能解决吗?如何动态创建这样的表达式?

最佳答案

public Expression<Func<TValue, bool>> CreateExpression<TValue, TCompare>(TValue value, TCompare compare)
{
var pv = Expression.Parameter(typeof(TValue), "data");
var compareProps = typeof(TCompare).GetProperties();

// First statement of the expression
Expression exp = Expression.Constant(true);

foreach (var prop in typeof(TValue).GetProperties())
{
// Check if the compare type has the same property
if (!compareProps.Any(i => i.Name == prop.Name))
continue;

// Build the expression: value.PropertyA == "A"
// which "A" come from compare.PropertyA
var eq = Expression.Equal(
Expression.Property(pv, prop.Name),
Expression.Constant(compareProps
.Single(i => i.Name == prop.Name)
.GetValue(compare)));

// Append with the first (previous) statement
exp = Expression.AndAlso(exp, eq);
}

return Expression.Lambda<Func<TValue, bool>>(exp, pv);
}

用法:

var value = new { Lang = "en", Name = "comedy"};

// The compareValue should have the same property name as the value,
// or the expression will just ignore the property
var compareValue = new { Lang = "en", Name = "comedy", Other = "xyz" };

// The create expression content is
// {data => ((True AndAlso (data.Lang == "en")) AndAlso (data.Name == "comedy"))}
bool isMatch = CreateExpression(value, compareValue).Compile()(value); // true

关于c# - 如何动态创建 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31282133/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com