In my list I have string with name and surname, how do I sort it by strings that contains X surname?
For example:
List<Student> students = new List<Student>()
{
new Student("John Doe"),
new Student("Lucy Novak")
};
With output: Students with surname Doe: John Doe
If you want filter out students with the second name Doe
you can put:
var result =
.Where(student => student
.Name
.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries)
.ElementAtOrDefault(1) == "Doe")
.ToList();
if you want to get all students, but sort them in such a way, that "Doe"
are on the top:
var result =
.OrderBy(student => student
.Name
.Split(' ', 3, StringSplitOptions.RemoveEmptyEntries)
.ElementAtOrDefault(1) != "Doe")
.ToList();
Note !=
- we can order by bool
, but we have false < true
In both cases we Split
stundent's Name
into at most 3
parts (first name, second name, all the rest names if they are). Then we try to obtain second name by .ElementAtOrDefault(1)
and compare it (or null
if student doen't have second name) with Doe
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.