加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何使用Linq-to-entities检索分层数据?

发布时间:2020-12-15 21:14:09 所属栏目:百科 来源:网络整理
导读:我想检索数据,并将其显示在有条件的(子项下面的子项)中. 这样定义的数据项:ID |标题|家长ID 我所做的是首先检索所有项目然后排序. 使用linq有更好的方法吗? protected void Page_Load(object sender,EventArgs e){ ListCategory list2 = new ListCategory(
我想检索数据,并将其显示在有条件的(子项下面的子项)中.
这样定义的数据项:ID |标题|家长ID

我所做的是首先检索所有项目然后排序.
使用linq有更好的方法吗?

protected void Page_Load(object sender,EventArgs e)
{          
    List<Category> list2 = new List<Category>();
    ContModel modeltx = new ContModel();

    var ret = modeltx.Categories.ToList();

     GetCategoryList(0,ret,list2);
     string str="";

     foreach (Category cat in list2)
     {
          str=str+cat.Title+"n";
         TextBox1.Text = str;
     }       
}


   private void GetCategoryList(int iCurID,int iDepth,List<Category> li,List<Category> newList)
    {
        Category tmp;
        string strOffset = "";

        foreach (Category cat in li)
        {
            if ((cat.ParentId) == iCurID)
            {
                for (int i = 1; i <= iDepth; i++)
                    strOffset = strOffset + "-";  

                strOffset = strOffset + cat.Title;

                tmp = cat;
                tmp.Title = strOffset;
                newList.Add(tmp);

                strOffset = "";
                GetCategoryList(cat.CategoryID,iDepth + 1,li,newList);
            }
        }
    }

更新:

如果数据的大小很大,我想使用分页怎么样?
排序之前我不能Page(.Skip(PageSize * PageIndex).Take(PageSize))

解决方法

我担心你必须在你的代码中对LINQ结果进行递归.根据表的大小和结构,您可能希望将整个表下拉到内存中(就像您正在做的那样)并在那里执行层次结构.如果您有一个非常大的表,您可能希望重复访问数据库.

有关更多信息,请阅读这篇精彩的文章:Storing Hierarchical Data in a Database

你的代码已经在内存中扁平化了.我建议在list2对象(包含展平的)数据上使用Skip(pSize * pIndex).Take(pSize).请注意,这可能会导致层次结构深入分页.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读