3

最近、それぞれが相互に関連付けられているページとナビゲーションメニューエントリのリストを並べ替える必要がありました。

それぞれNavigationPageプロパティがあります。それぞれPageNavigationプロパティがあります。それらは私のデータベースの外部キー参照です。

アイテムのNavigationリストとすべてのPageアイテムのリストがあります。問題は、Pageに関連付けられているかどうかに関係なく、アイテムNavigationのリストに保存されることです。Page

Page次のように並べ替えられたアイテムのリストを作成したいと思います。null以外のアイテムNavigationは、プロパティで並べ替えられPage.Navigation.Indexます。nullのあるアイテムは、プロパティ、次にプロパティでNavigation並べ替えられます。Page.TitlePage.ID

以下は私たちが現在行っていることであり、いくつかの例外を除いて、ほとんどの部分で機能します。私がこれに関して抱えている問題は、ナビゲーションが関連付けられていないページの重複したタイトルを処理しないことです。

List<Page> page1 = db.Navigations.OrderBy(n => n.Index).Select(n => n.Page).ToList();

List<Page> page2 = db.Pages.Where(p => !db.Navigations.Contains(p.Navigation)).ToList();

model.Pages = page1.Concat(page2).ToList();

これがいくつかのサンプルデータと期待される結果です

Pages Table (PageID, Title, Content)
0, "Home", "<html>This is a home page</html>"
3, "Some Page", "<html>This is some page.</html>"
2, "Some hidden page", "<html>This is some hidden page.</html>"
4, "Products", "<html>We've got products!</html>"
5, "aaaaa", "<html>This should be sorted to the top of pages with no nav</html>"

Navigations Table (PageID, Index)
0, 0
3, 2
4, 1

Output (PageID, Title, Content)
0, "Home", "<html>This is a home page</html>"
4, "Products", "<html>We've got products!</html>"
3, "Some Page", "<html>This is some page</html>"
5, "aaaaa", "<html>This should be sorted to the top of pages with no nav</html>"
2, "Some hidden page", "<html>This is some hidden page.</html"

これが見栄えの良い方法で、また手続き型構文の代わりにクエリ構文で実行できるかどうか知りたいです。

4

1 に答える 1

3

これで問題が解決すると思います。

model.Pages = db.Pages
  .OrderBy(p=>p.Navigation != null ? p.Navigation.Index : Int32.MaxValue)
  .ThenBy (p=>p.Title)
  .ThenBy (p=>p.PageID)
  .ToList();

または、この構文が好きな場合

var query = from p in db.Pages
            orderby p.Navigation != null ? p.Navigation.Index : Int32.MaxValue,
                       p.Title, 
                       p.PageID
            select p;

model.Pages = query.ToList();

ページは、Navigation.Indexが存在する場合は順序付けられ、Navigation.Indexがないページは、これらのページの後に表示されます(実際には、Navigation.IndexとしてInt32.MaxValueがあります)。Navigation.Indexがないものは一意の値(Int32.MaxValue)を持つようになったため、これらはTitle、次にPageIdの順に並べ替えられます。

于 2012-04-20T08:55:34.173 に答える