Linq Getting distinct values from a custom list
Do you want to learn how to get the distinct values from a list of data using LINQ. Here in this article I would be demonstrating one such example where I would be displaying the distinct names of employee from an employee list.
In this article we are going to see how to get the distinct values from a list of data. Here we are using a list of employees and displaying the distinct names of employee from the list. We are going to use Linq to get the distinct values.
1.Create an Employee class with EmpId,EmpName and Course datamembers as shown below:
public class Employee
{
public Employee()
{
}
public Employee(int id,string name,string courseName)
{
this.EmpId = id;
this.EmpName = name;
this.Course = courseName;
}
private int empId;
public int EmpId
{
get { return empId; }
set { empId = value; }
}
private string empName;
public string EmpName
{
get { return empName; }
set { empName = value; }
}
private string course;
public string Course
{
get { return course; }
set { course = value; }
}
}
2. Add the following directive at the top of the file:using System.Linq;
3. Add Employee objects to the List of Employees as shown:
List
lstEmployee.Add(new Employee(1, "rohit", ".Net"));
lstEmployee.Add(new Employee(2, "rohit", "Java"));
lstEmployee.Add(new Employee(3, "Akansha", ".Net"));
lstEmployee.Add(new Employee(4, "Teena", "Java"));
lstEmployee.Add(new Employee(5, "rohit", "Oracle"));
4.Using Linq get the distinct EmpName and store it in the lstEmp object. This object contains all the distinct Employee names.
List
(from empnames in lstEmployee.AsEnumerable()
select new{
Name = empnames.EmpName
}).Distinct().Select(x =>new Employee()
{ EmpName = x.Name }).ToList();
5.Display all the distinct employee names as shown below.
foreach (Employee emp in lstEmp)
{
Response.Write(emp.EmpName + " ");
}
Using Lamda Expression we can achieve the same result.