Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Select distinct records using Linq

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 482
    Comment on it

    We often need to select distinct records from a list or from database. In Linq, we can select distinct records from a list or collection using Distinct method.

    Suppose we have a list with the name Employees and we want to select only Distinct records from this list then this can be done by using Distinct method.

    Here is the code for this

     static void Main(string[] args)
            {
                List<string> employees = new List<string> { "Abhishek", "Shubham", "Sameer", "Shubham" };
                var distinctEmployees = employees.Distinct().ToList();
                foreach (var emp in distinctEmployees)
                {
                    Console.WriteLine(emp);
                }
                Console.Read();
            }

    In the above code, we are creating a list employees with employee names in which name Shubham is added twice. Now we want to get distict records out of the employees list.

    For this, we have used following statement

    var distinctEmployees = employees.Distinct().ToList();

    This statement will assign distinct records to distictEmployees variable. In the next step, we are iterating the distictEmployees variable and writing the values to console.

    The output will look like this

    Abhishek

    Shubham

    Sameer

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: