2

I have class grades that I need to check if a specific grade is pass or fail. This is the list of grades in order:

  1. A
  2. A-
  3. B+
  4. B
  5. B-

If B is the pass mark, and The student has B+, using the normal ordering, if I check if the studentGrade > passMark, then its going to say it is failed because the system orders the strings as follows:

  1. A
  2. A-
  3. B
  4. B+
  5. B-

How do I setup a custom comparer for ordering a list as the first list in c#?

1
  • 1
    What have you tried? A custom comparer is a logical choice to solve the problem, but you need to do some legwork here. Commented Jun 13, 2012 at 18:38

5 Answers 5

4

How about setting up your letter grades by numeric value?

  • A = 4.0
  • A- = 3.7
  • B+ = 3.3
  • B = 3.0

and so on....

Then order by numeric value rather than letter grade. 3.0 can be the pass mark.

Just a thought.

Sign up to request clarification or add additional context in comments.

Comments

3

You can create a custom class that implements IComparer<string>, and use it to do the ordering as needed.

That being said, grades are often handled numerically instead of via string comparisons. Using a numeric value would make this far simpler.

Comments

3

Using the sort method of the List<> class and providing a custom Comparison is the way to go (at least one way).

Comments

2

How about an Enum to give them a weight?

public enum ComparisonType
{ 
    A = 1, 
    AM = 2, 
    BP = 3,
    B = 4,
    BM = 5
}

It makes it easier when creating a custom comparer.

public class GradeComparer : IComparer {}

After that its a breeze by calling the .Sort() method on your list and voila.

Comments

-1

try this :

public class MyComparer : IComparer<MyObject>
{     
    public int Compare(string s1, string s2)
    {
          var grad1 = s1.Replace('+','1').Replace('-','2');
          var grad2 = s2.Replace('+','1').Replace('-','2');             
          if (grad1 > grad2)
              retun 1;
          else if (grad1 < grad2)
              return -1;
          else
              return 0;

    }
}


List<string> list = new List<string>{"A","A+","A-"};

var sortedList = list.OrederBy(o=>o,new MyComparer()).OrderBy(o=>o.Length);

1 Comment

You probably want to replace + with 0, make nothing append "1", and "-" with "2"...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.