我可以将表示变量的表达式传递给实例化对象时使用。
不需要这样:
class MyObject : IMyInterface { ... }
var list = db.MyObjects.Where(x => !x.IsDeleted).ToList();
var anotherList = list.Select(x => new AnotherObject() {
Id = x.Id,
Value = x.Value
});
我希望能够将一个
IMyInterface
对象列表转换为另一种类型的列表(以AnotherObject为例),并使用定义好的表达式进行转换,具体如下:var list = db.MyObjects
.Where(x => !x.IsDeleted)
.ToAnotherObjectList(x => x.Id, x => x.Value);
...
public static List<AnotherObject> ToAnotherObjectList<T>(
this IEnumerable<IMyInterface> list,
Expression id,
Expression value)
{
return list.Select(x => new AnotherObject() { Id = id, Value = value }).ToList();
}
我不确定如何实现这个。我知道可以使用反射来创建对象并通过字符串设置属性,但我不知道如何传递表达式。
更新
好吧,我以为我需要进行一些反射操作,但它比我想象的要简单。以下是在现实生活中有效的解决方案。
public static IEnumerable<AnotherObject> ToAnotherObject<T>(this IEnumerable<T> list, Func<T, int> getId, Func<T, string> getValue, Func<T, bool> getSelected = null) where T : IMyInterface
{
return list.Select(x => new AnotherObject {
Display = getValue(x),
Id = getId(x),
Selected = getSelected != null && getSelected(x),
});
}
where T : IMyInteface
对T
进行了限制。 - Paul Carlton