[英]Sorting a list that is contained in a sub-class
我正在嘗試按字母順序排序Chromes書簽,首先是文件夾,然后是網址
我有這些課程(傑森格里姆先生)
public class Bookmarks
{
public string Checksum { get; set; }
public Root Roots { get; set; }
public int Version { get; set; }
}
/// <summary>
/// Contains 'folders' such as 'Bookmarks bar' and 'Other bookmarks'
/// </summary>
public class Root
{
public RootItem Bookmark_bar { get; set; }
public RootItem Other { get; set; }
}
/// <summary>
/// A folder of bookmarks
/// </summary>
public class RootItem
{
public List<Child> Children { get; set; }
public string Date_added { get; set; }
public string Date_modified { get; set; }
public int Id { get; set; }
public String Name { get; set; }
public string Type { get; set; }
}
/// <summary>
/// Contains information about a specific bookmark
/// </summary>
public class Child
{
public List<Child> Children { get; set; }
public string date_added { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public String Type { get; set; }
public Uri Url { get; set; }
}
我使用JavaScriptSerializer反序列化和序列化JSON文件。 該文件被反序列化OK到Bookmarks類結構中。
現在我想對兩個列表RootItem.Children和Child.Children進行排序,以便所有文件夾首先出現,然后按字母順序排列所有文件夾。
我該怎么做?
將List.Sort(Comparison<T> comparison)
與自定義比較一起使用。
這是未經測試的代碼,因為我沒有您的反序列化結構,如果Child.ChildItem
可以為null,您可能需要使用一些空處理來增加它。
我還假設Child.Type告訴書簽是文件夾還是URL。 如果沒有,只需更改comparisson return child1.Type.CompareTo(child2.Type);
到文件夾/網址排序的東西。
public void SortChildren(List<Child> childList)
{
childList.Sort((child1, child2) =>
{
if (child1.Type == child2.Type)
{
// Sort by name
return child1.Name.CompareTo(child2.Name);
}
else
{
// Sort the type. If this sorts in reverse, swap child1 and child2
return child1.Type.CompareTo(child2.Type);
}
});
// Sort children recursively
foreach(var child in childList)
{
SortChildren(child.Children);
}
}
用...開始排序
SortChildren(Root.Other.Children);
編輯
一個更簡單的列表排序示例是
List<int> myInts = new List<int>{1,5,4,3,2};
myInts.Sort(); // default comparer
myInts.Sort((i1, i2) => { return i2.CompareTo(i1); }); // custom "reverse" comparison
如果您希望它們都在同一個列表中,那么您必須使用所需的屬性創建一個對象,例如MyListItem。
我想引用System.Linq;
然后你可以做一個select Children.Select(c => new MyListItem( Name = c.Name, etc )
的getter select Children.Select(c => new MyListItem( Name = c.Name, etc )
。
然后,您可以對URL執行相同操作,但附加.OrderBy(c => c.Url);
最后,您可以使用ToList()
和Append
最后一個列表添加到第一個列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.