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

本文关键字:泛型 创建 动态 投影 选择 Linq | 更新日期: 2023-09-27 18:31:51

所以我有一个函数,我将 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());
 }

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

您还需要传入一个转换函数:

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;
}