我正在使用实体框架并在数据库上执行查询,该数据库返回一家公司,而该公司又每个公司有很多联系人。
我有两种情况,我想对具有相同名字和姓氏的 MyContacts 进行分组。
虽然我可以遍历存储结果的新对象数组,但我使用的是实体框架,并且必须多次加载数据会很慢,所以如果可能的话,我更愿意在结果集。
计划是我可以遍历结果数组,对 MyContacts 对象进行更改,并将对象更新到 EF 存储库中。
第一种情况是按名称对联系人列表进行分组,但我不确定如何在不创建新类数据集的情况下进行分组。
第二种情况更复杂,我有一个 MyAccounts 列表(每个都有一个 MyContacts 列表),我想返回所有列表的 MyContacts,按名字和姓氏分组,并尽可能返回原始类。
非常感谢,克里斯。
我已经删除了数据访问,并在下面做了一个简单的例子:
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?