0

I am VERY new to programming, and am learning C#. Week 4!

Writing program asking for user input for:

  • Friends name
  • Phone
  • Month of Birth
  • Day
  • Year of birth.

Creating as an array of objects and using the IComparable to enable object comparison. Need to sort objects by string, alphabetically, and I think I have all the rest of the code except getting the string to compare. Here's what I have for the IComparable.CompareTo(Object o):

int IComparable.CompareTo(Object o)
{
    int returnVal;

    Friend temp = (Friend)o;
    if(this.Name > temp.Name)
        returnVal = 1;
    else
        if(this.Name < temp.Name)
            returnVal = -1;
        else returnVal = 0;
    return returnVal;
}

The error I receive when compiling is:

CS0019 Operator'>' cannot be applied to operands of type 'string' and 'string'.

Instructor is not much help, text doesn't synthesize this contingency.

2 Answers 2

3

Just delegate to String.CompareTo:

int IComparable.CompareTo(Object o) {
    Friend temp = (Friend)o;

    return this.Name.CompareTo(temp.Name);
}
Sign up to request clarification or add additional context in comments.

1 Comment

You should be aware that this performs “case-sensitive and culture-sensitive comparison using the current culture”, which may or may not be what's required.
0

This uses a couple language features you are probably not used to, but does make like a little easier:

people = people.OrderBy(person => person.Name).ToList();

Used like:

var rnd = new Random();
var people = new List<Person>();
for (int i = 0; i < 10; i++)
    people.Add(new Person { Name = rnd.Next().ToString() });

//remember, this provides an alphabetical, not numerical ordering,
//because name is a string, not numerical in this example.
people = people.OrderBy(person => person.Name).ToList();

people.ForEach(person => Console.WriteLine(person.Name));
Console.ReadLine();

Google LINQ [and remember to add 'using System.Linq;'] and Lambda's.

Comments

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.