2015-08-14 63 views
3

所以我試圖讓這個控制檯程序,你可以添加評論和評級給某本書。某些評論也可以提高。C# - 按列表中對象的屬性排序<T>

這裏是我的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; 
    } 

我試圖秩序的意見書列表中添加註釋書有我的評論對象的投票屬性有,但我似乎無法使其工作...

+0

如何使用SortedSet的,使用自定義的IComparer /的Comparer 實現其做初始化的基礎上,評論投票/評分比較? – elgonzo

回答

3

試試這個:

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

謝謝,這使它工作 –