none
How do I get unique values RRS feed

  • Question

  • Hi,

    I have a List<Employee> that contains employee's personal information as well as his/her department ID i.e. DepartmentId.

    I need to get a list of unique DepartmentId's for a foreach statement. I'd appreciate some help with the LINQ statement that would give me unique DepartmentId's.


    Thanks, Sam
    Wednesday, December 7, 2011 5:13 AM

Answers

  • Wednesday, December 7, 2011 2:54 PM
  • Hi imsam67;

    Assuming that the context instance is ctx and the table name is Employees then a query like the following would work.

    var deptIDs = (from emp in ctx.Employees
                   select emp.DepartmentId).Distinct().ToList();
                  
    The variable deptIDs is a distinct list of values of the data type of DepartmentId.

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Wednesday, December 7, 2011 8:44 PM

All replies

  • Wednesday, December 7, 2011 2:54 PM
  • Hi imsam67;

    Assuming that the context instance is ctx and the table name is Employees then a query like the following would work.

    var deptIDs = (from emp in ctx.Employees
                   select emp.DepartmentId).Distinct().ToList();
                  
    The variable deptIDs is a distinct list of values of the data type of DepartmentId.

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Wednesday, December 7, 2011 8:44 PM
  • Hi,

    Try with the below simple example to get distinct records

    List<Package> packages =new List<Package>                           

       {

         new Package { Company = "Coho Vineyard", Weight = 25.2 },

         new Package { Company = "Lucerne Publishing", Weight = 18.7 },

         new Package { Company = "Wingtip Toys", Weight = 6.0 },

        new Package { Company = "Adventure Works", Weight = 33.8 },

        new Package { Company = "Adventure Works", Weight = 33.8 },

        new Package { Company = "Adventure Works", Weight = 33.8 }

      };

     

     Console.WriteLine("\n Distinct Records");
     Console.WriteLine("--------------------");


      IEnumerable<string> distinct = (from c in packages

                                                           select c.Company

                                                       ).Distinct().ToList();


        foreach (string dis in distinct)
        {
               Console.WriteLine("{0}", dis);
         }


    PS.Shakeer Hussain
    Saturday, December 17, 2011 8:03 AM