【问题标题】:C# - Order by an Object's property in List<T>C# - 按 List<T> 中对象的属性排序
【发布时间】:2015-08-14 22:22:34
【问题描述】:

所以我正在尝试制作这个控制台程序,您可以在其中为某本书添加 cmets 和评级。某条评论也可以被点赞。

这是我的 Comment.cs

class Comment
{
    #region state
    private readonly string name;
    private readonly string commentary;
    private readonly uint rating;
    private uint votes;
    #endregion state
    #region constructor
    public Comment(string name , string commentary, uint rating)
    {
        this.name = name;
        this.commentary = commentary;
        this.rating = rating;
        this.votes = 0;
    }
    #endregion

    #region properties
    public string Name
    {
        get { return name; }

    }
    public string Commentary
    {
        get { return commentary; }
    }
    public uint Rating
    {
        get { return rating; }
    }
    public uint Votes
    {
        get { return votes; }
        private set { votes = value; }
    }

    #endregion

    #region behaviour
    public void VoteHelpfull()
    {
            Votes++;

    }
    public override string ToString()
    {

        string[] lines ={
                            "{0}",
                            "Rating: {1} - By: {2} voterating: {3}"
                        };
        return string.Format(
            string.Join(Environment.NewLine,lines),Commentary,Rating,Name,Votes);
    }

    #endregion

}

您可以根据它们在List&lt;Comment&gt; Comments 中的存储位置将它们添加到书籍中

class Book
{
    #region state
    private readonly string bookname;
    private readonly decimal price;
    private List<Comment> comments;
    #endregion

    #region constructor
    public Book(string bookname,decimal price)
    {
        this.bookname = bookname;
        this.price = price;
        comments = new List<Comment>();
    }
    #endregion 

    #region properties
    private List<Comment> Comments
    {
        get { return comments; }
        set { comments = value; }
    }
    public string Bookname
    {
        get { return bookname; }
    }
    public decimal Price
    {
        get { return price; }
    } 
    #endregion

    #region behaviours
    public void AddComment(string name, string commentary, uint rating)
    {
        Comments.Add(new Comment(name, commentary, rating));
    }
    public override string ToString()
    {

        string s = string.Format("{0} - {1} euro - {2} comments",Bookname,Price,Comments.Count);

        foreach (Comment c in Comments)
        {
            s += Environment.NewLine;
            s += c;

        }
        return s;
    }

我正在尝试通过我的评论对象的 votes 属性来订购一本书的 cmets 列表,但我似乎无法让它工作......

【问题讨论】:

  • 如何使用 SortedSet,使用自定义 IComparer / Comparer 实现进行初始化,该实现根据评论投票/评分进行比较?

标签: c# list object


【解决方案1】:

试试这个:

 foreach (Comment c in Comments.OrderBy(c=>c.Votes))
 {
    .....
 }

【讨论】:

    猜你喜欢
    • 2021-05-25
    • 2020-08-03
    • 1970-01-01
    • 2019-07-02
    • 2023-03-27
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多