Reputation: 13
I need to read a list of names in one line with ','
for example:
John Doe, Johnny Di, ...
I am a beginner so I don't really know how to properly read from a list but this is what I managed to scramble
var names = new List<string>();
string name1 = Console.ReadLine();
while (name1 != "")
{
names.Add(name1);
name1 = Console.ReadLine();
}
var res = from name in names
orderby name.Split(" ")[1]
ascending
select name;
Upvotes: 0
Views: 58
Reputation: 186728
Something like this:
var res = Console
.ReadLine()
.Split(',', StringSplitOptions.TrimEntries)
.OrderBy(name => name
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.LastOrDefault(),
StringComparer.OrdinalIgnoreCase)
.ToList(); // .ToArray(); if you want an array
Here we
Console.ReadLine()
- all names separated by commas (e.g. John Doe, Johnny Di, John Smith
),
while trimming each item (let be nice and tolerate spaces before and after commas like John Smith, Jack Doe
)Split
name
to get last name. LastOrDefault
for the last nameList<string>
) as a res
Upvotes: 1