Reputation: 116
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
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
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