c# - 从 Func<T> 返回匿名作为 .Select() 中的参数

标签 c# linq generics c#-3.0 anonymous-types

为了对方法进行“后处理”,我想将一个额外的函数导入到方法中。

如何导入返回匿名类型作为 .Select 扩展方法参数的 Func

表达式是匿名的,例如:

p => new
{
    ThumnailUrl = p.PicasaEntry.Media.Thumbnails[0].Attributes["url"],
    ImageUrl = p.PhotoUri
}

并且需要在参数??????并在 .Select(?????) 处执行

private void BindControl<T, U>(string uri, DataBoundControl target, ?????)
    where T : KindQuery, new()
    where U : PicasaEntity, new()
{
    PicasaFeed feed = CreateFeed<T>(uri);
    albumList.DataSource = GetPicasaEntries<U>(feed).Select(?????);
    albumList.DataBind();
}

更新:

最后我想这样调用它:

    string albumUri = PicasaQuery.CreatePicasaUri(PicasaUserID, PicasaAlbumID);
    BindControls<AlbumQuery, Album>(albumUri, albumList, ?????);

    string photoUri = PicasaQuery.CreatePicasaUri(PicasaUserID, PicasaAlbumID);
    BindControls<PhotoQuery, Photo>(photoUri, slideShow, ?????);

其他方法如下:

private PicasaFeed CreateFeed<T>(string uri) 
   where T : KindQuery, new()
{
    PicasaFeed feed = null;

    try
    {
        PicasaService service = new PicasaService(PicasaApplicationName);
        T query = new T();
        query.BaseAddress = uri;
        feed = service.Query(query);
    }
    catch (Exception ex)
    {
        //exception handling not shown
    }

    return feed;
}



private IEnumerable<T> GetPicasaEntries<T>(PicasaFeed feed) 
     where T : PicasaEntity, new()
{
    if(feed == null){
        return null;
    }

    IEnumerable<T> entries = null;
    string cacheKey = feed.Id.ToString();

    if(Cache.Get(cacheKey) == null)
    {
        entries = feed.Entries.Select(x => new T() { AtomEntry = x }).ToList();
    Cache.Insert(cacheKey, entries, 
              null, Cache.NoAbsoluteExpiration, new TimeSpan(0,20,0));
    }

    return entries;
}

最佳答案

匿名类型实际上只为本地使用而设计。在强类型语言中,不能被强类型化的类型并不真正被鼓励用于一般用途……它们只是动态世界中 c# 小舞的一部分。

你有两个选择。

创建强类型。

  class Entry
  {
    public string ThumnailUrl { get; set; }
    public string ImageUrl { get; set; }
  }

然后使用:

  p => new Entry 
  {
     ThumnailUrl = p.PicasaEntry.Media.Thumbnails[0].Attributes["url"],
     ImageUrl = p.PhotoUri
  }

或者称它为Object。然后使用反射来获取数据 - 我不推荐这样做。

关于c# - 从 Func<T> 返回匿名作为 .Select() 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5880748/

相关文章:

C# Azure 服务总线队列 OnMessage 回调

c# - 是否可以使用 LINQ 来检测重复的相邻字符?

c# - 使用 LINQ to SQL 执行更新/设置

java - 如果我实现 List 并在接受 List< 的方法中调用 add 会怎样?扩展父类(super class)型>

c# - 只获取列表中的最后一项

c# - 将 Kestrel 暴露于外界的风险

linq - 在 PowerShell 中查询 LINQ 样式的列表

java - 泛型通配符混淆

c# - WebAPI : 'IHttpActionResult' does not contain a definition for 'GetAwaiter'

c# - 日、月、日、年的日期格式