Updated:
I removed previous answer as I believe this is more what you're looking for. The ability to sort a list that you've received. Your question is still poorly asked, so I'm going to go off some assumptions you've implied. Those are:
- Utilize a hard-coded List.
- Sort the List.
- Display to a user.
The class you'll want to look at for the sort is List(T).Sort
it provides a clean, quick, and simple approach to accomplish the goal. Details can be found here.
I'm going to use a more practical scenario, we have a series of students that will require their score / grades be sorted before output to our user.
To begin will build our Student
object.
public class Student
{
public string Name { get; set; }
public int Score { get; set; }
public string Grade { get; set; }
}
So far our object is pretty simple, it contains:
- Name (Who it is)
- Actual score (Numeric Representation)
- Grade (Letter Representation)
Now we will implement the IComparable<Student>
to our Student
object. This will implicitly implement the following method:
public int CompareTo(Student other)
{
throw new NotImplementedException();
}
So we will remove the Exception
out of the method and implement:
if(other == null)
return 1;
else
return this.Score.CompareTo(other.Score);
This small amount of code will do the following:
- If the object is
null
it will be greater. - It will compare our current Property to our Parameter Value.
Now all we have to do for our implementation:
// Create Our List
List<Student> student = new List<Student>();
// Add our Students to the List
student.Add(new Student() { Name = "Greg", Score = 100, Grade = "A+" });
student.Add(new Student() { Name = "Kelli", Score = 32, Grade = "F" });
student.Add(new Student() { Name = "Jon", Score = 95, Grade = "A" });
student.Add(new Student() { Name = "Tina", Score = 93, Grade = "A-" });
student.Add(new Student() { Name = "Erik", Score = 82, Grade = "B" });
student.Add(new Student() { Name = "Ashley", Score = 75, Grade = "C" });
// Apply our Sort.
student.Sort();
// Loop through Our List:
foreach (Student placement in student)
listBox1.Items.Add(placement.Name + " " + placement.Score + " " + placement.Grade);
That will put them in a Ascending
order. You can tweak and configure to make it Descending
should you require it, or even more complex. Hopefully this is a nice starting point.
Also some items have OrderBy
or OrderByDescending
accessible. So you can actually do code like this to a Dictionary
.
student.OrderByDescending(s => s.Value);
You have a slew of possibilities, hopefully this gets you started and able to think about your implementation a bit.