user17595081
user17595081

Reputation: 13

List of names sorting them by LastName

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

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

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

  1. Read user input - Console.ReadLine() - all names separated by commas (e.g. John Doe, Johnny Di, John Smith)
  2. Split user input by , while trimming each item (let be nice and tolerate spaces before and after commas like John Smith, Jack Doe)
  3. Order items: we Split name to get last name. LastOrDefault for the last name
  4. Let's have a list (List<string>) as a res

Upvotes: 1

Related Questions