我在Linq to Sql的IRepository实现中有类似这样的代码:

var newlist = from h in list where h.StringProp1 == "1"
                      select new MyBusinessBO{
                          firstProp = h.StringProp1,
                          secondProp = h.StringProp2
                      };

到MyBusinessBO的投影并不困难,但是当业务对象具有许多属性时,投影代码将变得很冗长。同样,由于投影可以在存储库中的多个位置进行,因此我们打破了DRY原理。

有什么方法可以抽象出投影或将其替换为委托(delegate)?

IE。替换代码
                          firstProp = h.StringProp1,
                          secondProp = h.StringProp2

有可重复使用的东西?

最佳答案

Queryable.Select需要Expression<Func<T, U>>。您可以编写一个返回此方法的方法,并在进行转换的任何地方使用该方法。

public Expression<Func<DataObj, BusiObj>> GetExpr()
{
  return h => new BusiObj()
  {
    firstProp = h.StringProp1,
    secondProp = h.StringProp2
  };
}


 //get a local variable holding the expression.
Expression<Func<DataObj, BusiObj>> toBusiObj = GetExpr();

//use it thusly
var newList = (from h in list where h.StringProp1 == "1" select h)
  .Select(toBusiObj)
  .ToList();

//or
List<BusiObj> newList = list
  .Where(h => h.StringProp1 == "1")
  .Select(toBusiObj)
  .ToList();

10-08 00:04