Reputation: 572
I am trying to sort a list on the basis of a search string. But there seems to be some issue. Below is the code:
namespace ListDemo
{
class Program
{
static void Main(string[] args)
{
Employee e1 = new Employee {ID=1,Name="John",City="London" };
Employee e2 = new Employee { ID = 2, Name = "Mary", City = "NY" };
Employee e3 = new Employee { ID = 3, Name = "Dave", City = "Sydney" };
Employee e4 = new Employee { ID = 4, Name = "Kate", City = "Chicago" };
Employee e5 = new Employee { ID = 5, Name = "Sheela", City = "Delhi" };
List<Employee> listEmployee = new List<Employee>();
listEmployee.Add(e1);
listEmployee.Add(e2);
listEmployee.Add(e3);
listEmployee.Add(e4);
listEmployee.Add(e5);
Console.WriteLine("Enter the name via which you wana sort?");
string searchString = Console.ReadLine();
Console.WriteLine("####################Sorted List Starts##############");
var items = from element in listEmployee
orderby element.Name.Equals(searchString)
select element;
foreach (var i in items)
{
Console.WriteLine(i.Name);
}
Console.ReadLine();
}
}
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
}
I have an Employee class with 3 public properties, ID, Name and City. I created a list of Employees with some dummy data in it.
Now I want the user to enter a search string, which will actually be a name, and if the list contains that name, it should sort the list as according to the search string.
For ex: if a user has entered name as 'John', then the revised list should show John as first item and so on.
The code which I have written behaves abnormally.
Upvotes: 1
Views: 1398
Reputation: 24903
Firstly, sort by equals in descending order (it means, that it will be firt in result), and others sort by ID to save original order (or, you can use any other property for ordering):
var items = listEmployee
.OrderByDescending(e => e.Name.Equals(searchString))
.ThenBy(e => e.ID).ToArray();
Upvotes: 5