Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

C# C# Streams and Data Processing Serialization Top Ten Scorers

Aaron Selonke
Aaron Selonke
10,323 Points

iComparible vs iComparer vs Linq

Hi there, I was pretty much a blank slate to the iComparer used in the video. After Checking out documentation and youtube videos for an hour I came to two hypothesis.

1) I tried to do this with the iComparable method first, and it was impossible because the PointsPerGame is a floating point variable. Can we get the same result with iComparable?

2) iComparer(and iComparable) are obsolete because we can call linq expressions on Lists (this is possible becuase List<t> implements the iEnumerable class).
Do I have that right?

Here is the solution (that I got from notes I took on an earlier Carling course)

public static List<Player> GetTopTenPlayers(List<Player> players)
       {
            var _Players = players.OrderByDescending(a => a.PointsPerGame).Take(10).ToList();
            return _Players;
        }

1 Answer

Steven Parker
Steven Parker
220,925 Points
  1. iComparable (or IComparer) can be used with any type of object (including floating point numbers). The restriction is that the result of the comparison function must be an integer. The video shows a good example of an iComparer being constructed that compares two Player objects. But it returns integer results.
  2. LINQ does not make iComparable (or IComparer) obsolete, but it does offer additional choices of ways to accomplish certain tasks (such as your sort solution).
Aaron Selonke
Aaron Selonke
10,323 Points

The PointsPerGame property on the Player class is a type double. The values for the different players all have decimals.
The iComparer seems to be returning double for the PointsPerGame properties for each player.

I kind of butcherd my code and completely removed the Icomparer Interface from the player class, So I won't have anything to paste here.