按名称和日期作为键在C#中对字典进行排序?

时间:2018-06-14 08:30:16

标签: c# class datetime dictionary

大家好我需要你的帮助。我在uni上有一个关于排序字典的任务。 它的属性是:

Dictionary<string, Book> nameAndDate = new Dictionary<string, Book>(); 类Book具有属性:

 class Book
{
    public string NAME;
    public string Date;
    public DateTime DateAsDate;
    public Book(string bookName , string date,DateTime dateAsDate)
    {
        this.NAME = bookName;
        this.Date = date;
        this.DateAsDate = dateAsDate;
    }
}

所以我的问题是我如何通过提升来对键进行排序,这样当我给这些书一个名字和一个日期时,它会像这样写出来

HP1 -> 26.06.1997
HP7 -> 21.07.2007
AC -> 20.11.2009

1 个答案:

答案 0 :(得分:0)

您可以使用LINQ以您想要的方式订购您的独角兽。例如,在下面的代码中,我按日期然后按名称对您的图书字典进行排序,以便我有相同的输出:

using System;
using System.Linq;
using System.Collections.Generic;

namespace ConsoleApp5
{
class Book
{
    public string Name;
    public DateTime Date;
    public Book(string bookName, DateTime dateAsDate)
    {
        this.Name = bookName;
        this.Date = dateAsDate;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var nameAndDate = new Dictionary<string, Book> {
            {"HP1", new Book("HP1", new DateTime(1997,6,26)) },
            {"HP7", new Book("HP1", new DateTime(2007,7,21)) },
            {"AC", new Book("AC", new DateTime(2009,11,20)) },
        };

        foreach (var book in nameAndDate.OrderBy(b => b.Value.Date).ThenBy(b => b.Value.Name))
        {
            Console.WriteLine($"{book.Key} -> {book.Value.Date.ToString("dd.MM.yyyy")}");
        }
        Console.ReadKey();
    }
}
}