So my ArrayList looks like this:
using System.Collections;
[...]
//in main:
Student s01 = new Student
{
name = "John",
surname = "Doa"
};
Student s02 = new Student
{
name = "John",
surname = "Doe"
};
Student s03 = new Student
{
name = "John",
surname = "Doi"
};
Student s04 = new Student
{
name = "John",
surname = "Doo"
};
Student s05 = new Student
{
name = "John",
surname = "Dou"
};
ArrayList studentsList = new ArrayList();
studentsList.Add(s03);
studentsList.Add(s04);
studentsList.Add(s05);
studentsList.Add(s01);
studentsList.Add(s02);
Student.cs:
class Student : IPerson
{
public string name;
public string surname;
public void Describe()
{
Console.WriteLine("{0} {1}", name, surname);
}
I'd like to sort my objects in studentsList by surname and write down both name + surname in foreach loop. I know that studentsList.Sort(); won't work, because it doesn't know in what way it should compare each object to other -
and that's where I'm stuck, because I don't really know how to write new comparer that's using value of field of object in arrayList. I don't even know how to start.
I have to use ArrayList, but I don't have to sort it directly (I can use casting I guess) - in the end it must look like:
1. John Doa
2. John Doe
3. John Doi
4. John Doo
5. John Dou
Would be great to Sort() studentsList, because I'd be able to do something like this:
int i = 0;
foreach (Student s in studentsList)
{
i++;
Console.Write("{0}. ", i);
s.Describe();
}
using System.Linqfor it to work.OfType<Student>()call. But please be aware thatArrayListis very rarely used in real code these days - it's been mostly-obsolete since 2005.