如何在C#中使用Linq从泛型创建动态选择投影?

时间:2013-09-17 16:27:29

标签: c# linq select projection

所以我有一个函数,我将Func调用回来。我还想添加某种选择投影,以便能够在对象上进行投影,这意味着我只会执行一次数据库调用。该函数看起来像这样:

public T Get<T>(string id, Func<T> getItemCallback) where T : class
{
    item = getItemCallback();
    if (item != null)
    {
        doSomeThing(item);
        // Here I would like to call something else that is 
        // expecting a specific type.  Is there way to pass in a
        // dynamic selector?
        doSomethingElse(item.Select(x => new CustomType { id = x.id, name = x.name }).ToList());
    }
    return item;
}

void doSomethingElse(List<CustomType> custom)
{
    ....
}

Leme展示了我现在如何调用它可能会有所帮助:

public List<MyDataSet> GetData(string keywords, string id)
{
    return _myObject.Get(
       id, 
       () => db.GetDataSet(keywords, id).ToList());
    // Perhaps I could add another parameter here to 
    // handled the projection ????
}

感谢里德,我想出来......看起来像这样:

public T Get<T>(string id, Func<T> getItemCallback, Func<T, List<CustomType>> selector) where T : class
{
     item = getItemCallback();
     if (item != null)
     {
          doSomething(item);
          var custom = selector(item);
          if (custom != null)
          {
              doSomethingElse(custom);
          }
     }
     return item;
 }

电话看起来像:

 public List<MyDataSet> GetData(string keywords, string id)
 {
     return _myObject.Get(
         id,
         () => db.GetDataSet(keywords, id).ToList(),
         x => x.Select(d => new CustomType { id = d.ReferenceId, name = d.Name })
               .ToList());
 }

1 个答案:

答案 0 :(得分:2)

您还需要传递转换函数:

public T Get<T>(string id, Func<T> getItemCallback, Func<T, List<CustomType>> conversion) where T : class
{
    item = getItemCallback();
    if (item != null)
    {
        doSomeThing(item);

        if (conversion != null)
            doSomethingElse(conversion(item));
    }
    return item;
}