我需要将一个列表转换成字典。在c#中,可以使用以下语法来完成:
var dictionary = myList.ToDictionary(e => e.Id);
我不知道id字段的名称,因为我正在创建一些代码来遍历一个对象及其子对象/列表并将它们附加到我的dbcontext中。
我已经有了确定我的关键值的属性名称的代码,但是为了测试,我可以只使用“Id”(其他可能不同)
所以我需要基本上创建这个字符串"c => e.Id"到一个Func,但我不确定参数是什么用于什么对象。
到目前为止,我有这个
public static Expression<Func<T, bool>> strToFunc<T>(string propName)
{
Expression<Func<T, bool>> func = null;
var prop = typeof(T).GetProperty(propName);
ParameterExpression tpe = Expression.Parameter(typeof(T));
var left = Expression.Property(tpe, prop);
return func;
}
希望擅长表达式的专家能够提供帮助。
先行致谢。
Expression<Func<SomeType, bool>> tmp = x => x.SomeProperty;
,您将能够在调试器中查看tmp
对象,这将帮助您找出所需的部分。另外,如果您想要创建一个表达式,为什么函数是<T, bool>
?我会期望是<TKey, TValue>
。 - Scott Chamberlainvar dictionary = myList.ToDictionary(e => e.GetType().GetProperty(propName).GetValue(e));
的操作呢? - Innat3