c# - 缓存 Linq 查询问题

标签 c# asp.net linq ienumerable

我正在为 cms 创建一个论坛包并查看缓存一些查询以帮助提高性能,但我不确定缓存下面是否会帮助/做下面应该做的事情(顺便说一句:Cachehelper 是一个简单的帮助器类,只是从缓存中添加和删除)

          // Set cache variables
        IEnumerable<ForumTopic> maintopics;

        if (!CacheHelper.Get(topicCacheKey, out maintopics))
        {
            // Now get topics
            maintopics = from t in u.ForumTopics
                          where t.ParentNodeId == CurrentNode.Id
                          orderby t.ForumTopicLastPost descending
                          select t;
            // Add to cache
            CacheHelper.Add(maintopics, topicCacheKey);
        }
        //End Cache

        // Pass to my pager helper
        var pagedResults = new PaginatedList<ForumTopic>(maintopics, p ?? 0, Convert.ToInt32(Settings.ForumTopicsPerPage));

        // Now bind
        rptTopicList.DataSource = pagedResults;
        rptTopicList.DataBind();

linq 不是只有在枚举时才执行吗?那么上面的方法行不通吗?因为它只是在我将它传递给分页助手时才枚举,分页助手根据查询字符串值“p”获取()一定数量的记录

最佳答案

您需要枚举结果,例如通过调用 ToList() 方法。

maintopics = from t in u.ForumTopics
             where t.ParentNodeId == CurrentNode.Id
             orderby t.ForumTopicLastPost descending
             select t;
// Add to cache
CacheHelper.Add(maintopics.ToList(), topicCacheKey);

关于c# - 缓存 Linq 查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4871450/

相关文章:

c# - 在 Medium Trust 中调用内部方法

c# - 如何在 GridView Pager 或 DataPager 中创建 'Show All' 按钮

javascript - 我认为我的网站已被感染

c# - 如何检查从此 Linq 查询中检索到的值作为 .ToLower()?

c# - 隐式与显式接口(interface)实现

c# - [UWP][MVVM] 在窗口中的框架中导航

c# - StreamReader ReadLineAsync 忽略回车并挂起

c# - 无法在 ASP.Net 中获取当前用户 IP

linq - 使用 lambda 选择类(class)中的最佳成绩

c# - 在调用 ToList() 或 Count() 之前检查 LINQ Where() 是否返回任何内容