Skip to content

Instantly share code, notes, and snippets.

Created March 25, 2011 03:55
Show Gist options
  • Save anonymous/886340 to your computer and use it in GitHub Desktop.
Save anonymous/886340 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Issue
{
public string ID { get; set; }
public string Date { get; set; }
public string ParentID { get; set; }
public override string ToString()
{
return "id=" + ID + " date=" + Date + " parent=" + ParentID;
}
}
class Program
{
static void Main(string[] args)
{
var dataList = new List<Issue>()
{
new Issue(){ID = "0", Date = "0", ParentID = ""},
new Issue(){ID = "1", Date = "3", ParentID = ""},
new Issue(){ID = "2", Date = "4", ParentID = ""},
new Issue(){ID = "20", Date = "6", ParentID = "2"},
new Issue(){ID = "21", Date = "2", ParentID = "2"},
new Issue(){ID = "22", Date = "3", ParentID = "2"},
new Issue(){ID = "220", Date = "4", ParentID = "22"},
new Issue(){ID = "221", Date = "5", ParentID = "22"},
new Issue(){ID = "3", Date = "5", ParentID = ""},
new Issue(){ID = "4", Date = "8", ParentID = ""},
new Issue(){ID = "5", Date = "2", ParentID = ""},
new Issue(){ID = "50", Date = "3", ParentID = "5"},
new Issue(){ID = "6", Date = "1", ParentID = ""},
new Issue(){ID = "60", Date = "2", ParentID = "6"},
new Issue(){ID = "7", Date = "9", ParentID = ""},
};
var sortedList = test2(dataList);
sortedList.ForEach(i => Console.WriteLine(i));
Console.Read();
}
static private List<Issue> test2(List<Issue> list)
{
// リスト全体を日付でソートする
// 日付順を保ったまま親がいないissueの新しいリストを作る
// 残ったissueは親を探して日付順を保ったまま親の次の位置に挿入する
// IDからissueを検索するためのテーブル
var table = list.ToDictionary(issue => issue.ID, issue => issue);
// 日付でソートする
var sortedList = list.OrderBy(issue => issue.Date).ToList();
// 新しいリストを作成
var parentChildRelationship = new List<Issue>();
// 親のいないissueを探して新しいリストに追加
var parentsList = sortedList.Where(issue => !table.ContainsKey(issue.ParentID));
parentChildRelationship.AddRange(parentsList);
// 追加したissueはソート済みリストから削除する
sortedList.RemoveAll(issue => parentsList.Contains(issue));
// ソート済みリストの要素がなくなるまで繰り返す
while (sortedList.Count != 0)
{
// リストの先頭の親の位置を探す
var parentID = sortedList[0].ParentID;
var parentIndex = parentChildRelationship.IndexOf(table[parentID]);
// 処理対象の親を持つissueを探す
var childList = sortedList.Where(issue => issue.ParentID == parentID);
// 子のリストを親の次の位置にインサートする
parentChildRelationship.InsertRange(parentIndex+1, childList);
// ソート済みリストからインサート済みの子を削除する
sortedList.RemoveAll(issue => childList.Contains(issue));
}
return parentChildRelationship;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment