2010年9月27日

Enumerate HierarchicalDataSource

ASP.NET 提供了很好的 SiteMap 機制,不過想以二維的方式來呈現 SiteMap,例如下列兩組 menu,分別以章節及索引不同的方式來條列,便需要利用到巡覽 DataSource 的技術了。

Home
Chapter One
Topic 1-1
Topic 1-2
Topic 1-3
Chapter Two
Topic 2-1
Topic 3-2
Index
A
Topic 1-2
C
Topic 1-1
Topic 2-2
N
Topic 1-3
Topic 2-1


我幫 Web.sitmap 增加了 index 的屬性,使巡覽時,可以依照 index 的第一個字母來分類。


    
      
      
        
        
        
        
      

      
        
        
      

    



下列程式,即是巡覽 XmlDataSource 的程式片段。
        public IEnumerable〈IGrouping〈char, XmlElement〉〉 CreateGroupingList(IDataSource dataSource)
        {
            List〈XmlElement〉 elementList = new List〈XmlElement〉();

            IHierarchicalDataSource hSource = dataSource as IHierarchicalDataSource;
            if (hSource != null)
            {
                HierarchicalDataSourceView hView = hSource.GetHierarchicalView(String.Empty);
                if (hView != null)
                {
                    IHierarchicalEnumerable hEnumerable = hView.Select();
                    ReadRecursive(hEnumerable, elementList);
                }
            }

            return elementList.OrderBy(p => p.Attributes["index"].Value).GroupBy(p => p.Attributes["index"].Value[0]);
        }


        private void ReadRecursive(IHierarchicalEnumerable enumerable, List〈XmlElement〉 elementList)
        {
            foreach (IHierarchyData item in enumerable)
            {
                if (item.Item is XmlElement)
                {
                    XmlElement element = item.Item as XmlElement;
                    if (element.Attributes["title"] != null && element.Attributes["index"] != null &&
                        element.Attributes["index"].Value.Length > 0)
                        elementList.Add(item.Item as XmlElement);
                }

                if (item.HasChildren)
                    ReadRecursive(item.GetChildren(), elementList);
            }
        }

沒有留言:

Deploying Vue & .NET with Google OAuth on GCP Cloud Run

Deploying Vue & .NET with Google OAuth on GCP Cloud Run Deploying Vue & .NET with Google OAuth on GCP Cloud Run...