DEV Community

Dejan Jovancevic
Dejan Jovancevic

Posted on

refactoring C# code advices

Hello guys, i'll pay close attention of any post that can closely help anyone interested in .net and c#.

Top comments (2)

Collapse
 
dejan_jovancevic_ns profile image
Dejan Jovancevic • Edited

my brainer for tonight is how to refactor this snippet to work with high performance if 1 million items are in. it's about books ratings.

public class Book
{
    public string Title { get; set; }
    public double Upvotes { get; set; }
    public double Downvotes { get; set; }
    public double PublisherStars { get; set; }
}

public IList<Book> TopRankList(IList<Book> books, int rankListLength)
{
    var rankedBooks = (
        from book in books
        let readerVotes = book.Upvotes - book.Downvotes
        let rank = (book.PublisherStars / 10 * 0.5) + (readerVotes * 0.5)
        orderby rank descending 
        select book
    ).Take(rankListLength);

    return rankedBooks.ToList();
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
elanatframework profile image
elanatframework

Hello

I rewrote a foreach code in parallel, the execution speed improved from 35 seconds to 7 seconds.

If I were you, I would use stored procedure; then I would use a separate table (or view) based on the score (complex you use) that would automatically update every 24 hours and update the list.