Omar Ruder
Omar Ruder

Reputation: 116

For my selectlist with multiple values per entry, how can I handle empty entries?

var studentInfo = _context.Student
    .Select(s =>
    new
    {
        Id = s.Id,
        Name = s.FirstName + " " + s.SurName + " " + s.LastName + " - " + s.StudentCode
    });

ViewBag.Students = new SelectList(studentInfo, "Id", "Name");

This is my code, it works fine for people who have a surname. But if the surname is empty, the selectlist entry displays no information at all, how can I prevent this?

Upvotes: 1

Views: 81

Answers (2)

ahybertz
ahybertz

Reputation: 574

This might also work - including removing the leftover spaces if SurName is not there :)

var students = new List<Student>() 
{ 
    new Student() { FirstName = "John", SurName = "Wick", LastName = "Doe", StudenCode = "666" }, 
    new Student() { FirstName = "James", LastName = "Bond", StudenCode = "0007" } 
};

var formattedStudents = students.Select(p => new { Name = Regex.Replace($"{p.FirstName} {p.SurName} {p.LastName} - {p.StudenCode}", 
                                                                        @"\s+"," ", 
                                                                        RegexOptions.Compiled) });

Upvotes: 0

Leszek Mazur
Leszek Mazur

Reputation: 2531

The easy way:

var studentInfo = _context.Student
    .Select(s =>
    new
    {
        Id = s.Id,
        Name = string.IsNullOrEmpty(s.SurName)
            ? s.FirstName + " " + s.LastName + " - " + s.StudentCode
            : s.FirstName + " " + s.SurName + " " + s.LastName + " - " + s.StudentCode
    });

ViewBag.Students = new SelectList(studentInfo, "Id", "Name");

Upvotes: 1

Related Questions