C# - 在 List<T> 中按照对象属性排序

3

我正在尝试制作一个控制台程序,可以向某本书添加评论和评分。某个评论也可以得到投票。

以下是我的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<Comment> 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;
    }

我正在尝试按照我的评论对象的投票属性来对一本书的评论列表进行排序,但似乎无法使其工作...


使用SortedSet<T>如何?它可以用自定义的IComparer<T>/Comparer<T>实现进行初始化,根据评论投票/评分进行比较。 - user2819245
1个回答

3

试试这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接