I am using Entity Framework and perform a query on a database that returns a company which in turn has many contacts per company.
I have the two scenarios where i want to group the MyContacts which have the same first and last name.
Whilst i can loop through an array of new objects where the result is stored, I am using Entity Framework and it will be slow to have to load data more than once, so if possible I would prefer to maintain the objects as-is in a result set.
The plan is i can loop through the results array, make a change to the MyContacts object, and update the object into the EF repository.
The first scenario is grouping a contact list by name, but i am unsure on how to group without making a new class dataset.
The second scenario is more complex, i have a list of MyAccounts (each of which has a list of MyContacts), i would like to return the MyContacts for all the list, grouped by first and lastname, with the original classes returned if possible.
Many thanks, Chris.
I have removed data access and made a simple example below:
class MyAccount
{
public string accountName { get; set; }
public List<MyContact> Contacts { get; set; }
}
class MyContact
{
public string firstname { get; set; }
public string lastname { get; set; }
}
MyContact contactA = new MyContact() { firstname = "Chris", lastname = "b", ID = 100 };
MyContact contactB = new MyContact() { firstname = "Chris", lastname = "b", ID = 101 };
MyContact contactC = new MyContact() { firstname = "Peter", lastname = "Bread", ID = 102 };
MyContact contactD = new MyContact() { firstname = "James", lastname = "apple", ID = 103 };
MyContact contactE = new MyContact() { firstname = "Richard", lastname = "Brian", ID = 104 };
MyContact contactF = new MyContact() { firstname = "James", lastname = "apple", ID = 105 };
List<MyContact> contacts = new List<MyContact>();
contacts.AddRange(new MyContact[] { contactA, contactB, contactC, contactD, contactE, contactF } );
// how do i get a list of items, grouped by same first and lastname?
MyAccount companyA = new MyAccount() { accountName = "CompanyA", Contacts = new List<MyContact>() };
companyA.Contacts.AddRange(new MyContact[] { contactA, contactB, contactC });
MyAccount companyB = new MyAccount() { accountName = "CompanyB", Contacts = new List<MyContact>() };
companyB.Contacts.AddRange(new MyContact[] { contactA, contactB, contactC });
MyAccount companyC = new MyAccount() { accountName = "CompanyB", Contacts = new List<MyContact>() };
companyB.Contacts.AddRange(new MyContact[] { contactA, contactB, contactC, contactD, contactE });
List<MyAccount> companyList = new List<MyAccount>(new MyAccount[] { companyA, companyB, companyC });
// from the companyList, is there any way to get a list of MyContact types grouped by duplicate first and lastname?
Try this…
Now you get IEnumerable of Lists.