Click here to Skip to main content
15,888,320 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm new to using LINQ. Basically I have a Employee Collection Object, which contains a number of employees. Each employee then has a Contact Collection as each employee could have a number of contact numbers/email. The link between the two is a ContactID. How would I go about using LINQ to retrieve some data from the Employee Collection and the rest of the data from the Contact Collection.
Not sure if how I have explains that will make sense to anybody else, but any feedback would be great.
Thanks
Posted
Comments
Sergey Alexandrovich Kryukov 15-Apr-13 14:39pm    
What is the problem? Duplicates? Something else?
—SA
BillWoodruff 17-Apr-13 4:00am    
Are you saying each item in the Contact Collection within every instance of the Employee Class: is a ContactID ?

What exactly is the form, structure, type, etc. of the ContactID ?

1 solution

Hi,
This is an attempt to code your scenario.

C#
class Program
   {
       static void Main(string[] args)
       {
           IEnumerable<Employee> empCollection = null;

           // populate the employee collection
           // now if you want to get primary contact of each employee

           var result = from e in empCollection
                        select new
                        {
                            EmployeeName = e.Name,
                            PrimaryContact = e.Contacts.Select(c => c.IsPrimaryContact).First()
                        };
           // result will be the IEnumerable<anonymoustype>, which contains EmployeeName and the associated primary contacts
       }
   }

   public class Employee
   {
       public string Name { get; set; }

       public IEnumerable<Contact> Contacts { get; set; }
   }

   public class Contact
   {
       public int ContactID { get; set; }

       public string EmailId { get; set; }

       public string Telephone { get; set; }

       public bool IsPrimaryContact { get; set; }
   }


Hope it helps :)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900