【发布时间】:2009-11-16 19:20:20
【问题描述】:
我需要将下面的代码翻译成一个表达式,我会解释原因:
results = results.Where(answer => answer.Question.Wording.Contains(term));
结果是 IQueryable
问题是 ISurveyQuestion
措辞是字符串
问题是,问题并不总是 LINQ to SQL 属性的名称。
这将为我提供实际 ISurveyQuestion 属性的 PropertyInfo
private static PropertyInfo FindNaturalProperty<TMemberType>(Type search)
{
IDictionary<string,PropertyInfo> properties = new Dictionary<string,PropertyInfo>();
search.GetProperties().Each(prop =>
{
if (null != prop.PropertyType.GetInterface(typeof(TMemberType).Name))
properties.Add(prop.Name, prop);
});
if (properties.Count < 1) throw new ArgumentException(String.Format("{0} has no properties of type {1}", search.Name, typeof(TMemberType).Name));
if (properties.Count == 1) return properties.Values.First();
search.GetInterfaces().Each(inter =>
{
inter.GetProperties().Each(prop =>
{
if (null != prop.PropertyType.GetInterface(typeof(TMemberType).Name))
properties.Remove(prop.Name);
});
});
if (properties.Count < 1) throw new ArgumentException(String.Format("{0} has no properties of type {1} that are not members of an interface", search.Name, typeof(TMemberType).Name));
if (properties.Count > 1) throw new AmbiguousMatchException(String.Format("{0} has more than one property that are of type {1} and are not members of an interface", search.Name, typeof(TMemberType).Name));
return properties.Values.First();
}
获得 PropertyInfo 后,如何将其转换为表达式树?
编辑:
我基本上需要的是:
results = results.Where(answer => answer.GetQuestionProperty().GetValue(answer).Wording.Contains(term));
但这不起作用,所以我需要自己构建表达式树,用于 linq-to-sql。
【问题讨论】:
标签: linq-to-sql lambda expression-trees