user8670136
user8670136

Reputation:

how to get only the first name of a list in alphabetical order?

I have a list with students and want to get only the first student from the alphabet.

My following Code gives me all current students in alphabetical order, but I only want the first one.

for (char letter = 'A'; letter <= 'Z'; letter++)
{
    Console.WriteLine(letter); 

    foreach (var studentName in _students) 
    {
        if (studentName)                   
        {
            Console.WriteLine(studentName.Lastname + " " + studentName.Firstname);                      
        }
    }
}

Upvotes: 0

Views: 487

Answers (2)

LenglBoy
LenglBoy

Reputation: 1441

If you _students is a List<String>, this will return the first one in the sorted list.

student1 = _students.sort()[0]

If you want to sort by property List<Student> (Sort by FirstName):

List<Student> sortedList = _students.OrderBy(s=>s.FirstName).ToList();

Now ypu can get the first one by _sortedList[0].


You don´t need alphabetical loop anymore. This snippet will print all students in alphabetical order:

_students = _students.OrderBy(s=>s.FirstName).ToList();  // sorting and saving
_students.ForEach(s => Console.WriteLine(s.FirstName + " " + s.LastName)); // printing each element

If you want the first Student for each letter you can filter like this:

_students.Where(s => searchList.Any(s=>s.StartsWith(letter)))[0];

Write this into your letter-loop and every first one gets returned. Be careful null or Exception can be thrown if there is no result for [0].

Upvotes: 0

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

You can use Linq to create a sorted enumerable:

var sortedStudents = _students.OrderBy(s => s.LastName, StringComparer.InvariantCultureIgnoreCase).ThenBy(s => s.FirstName, StringComparer.InvariantCultureIgnoreCase);

This will sort the students A-Z ignoring diacritics.

Then you can simply iterate through it to print all:

foreach (var student in sortedStudents)
{
    Console.WriteLine(student.LastName + " " + student.FirstName);
}

Or just take the first one:

var firstStudent = sortedStudents.FirstOrDefault(); // returns the first student or null.

And finally, all in one statement:

var firstStudent  = _students.OrderBy(s => s.LastName, StringComparer.InvariantCultureIgnoreCase).ThenBy(s => s.FirstName, StringComparer.InvariantCultureIgnoreCase).FirstOrDefault();

Upvotes: 2

Related Questions