【发布时间】:2018-10-02 20:35:39
【问题描述】:
我需要退回所有客户以及所有有效联系人:
联系人类:
public class Contact
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsValid { get; set; }
}
客户类别:
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
public List<Contact> Contacts { get; set; }
}
客户名单:
List<Customer> customers = new List<Customer>
{
new Customer
{
ID = 1,
Name = "Ahmed",
Contacts = new List<Contact>
{
new Contact { ID = 1 , Name = "A", IsValid = true },
new Contact { ID = 2 , Name = "B", IsValid = true },
new Contact { ID = 3 , Name = "C", IsValid = true }
}
},
new Customer
{
ID = 2,
Name = "Mohamed",
Contacts = new List<Contact>
{
new Contact { ID = 4 , Name = "D", IsValid = true },
new Contact { ID = 5 , Name = "E", IsValid = true },
new Contact { ID = 6 , Name = "F", IsValid = false }
}
},
new Customer
{
ID = 3,
Name = "Ali",
Contacts = new List<Contact>
{
new Contact { ID = 7 , Name = "X", IsValid = false },
new Contact { ID = 8 , Name = "Y", IsValid = false },
new Contact { ID = 9 , Name = "Z", IsValid = false }
}
}
};
应用 LINQ 后需要的结果:
List<Customer> customersResult = new List<Customer>
{
new Customer
{
ID = 1,
Name = "Ahmed",
Contacts = new List<Contact>
{
new Contact { ID = 1 , Name = "A", IsValid = true },
new Contact { ID = 2 , Name = "B", IsValid = true },
new Contact { ID = 3 , Name = "C", IsValid = true }
}
},
new Customer
{
ID = 2,
Name = "Mohamed",
Contacts = new List<Contact>
{
new Contact { ID = 4 , Name = "D", IsValid = true },
new Contact { ID = 5 , Name = "E", IsValid = true }
}
},
new Customer
{
ID = 3,
Name = "Ali",
Contacts = new List<Contact>()
}
};
我需要返回每个客户,每个客户只包含 IsValid = true 联系人,客户不包含 IsValid 联系人显示没有联系人,LINQ 怎么做到这一点?
【问题讨论】:
-
你能提供一个你迄今为止尝试过的样本吗?
-
List
customersResult = customers.Where(c=>c.Contacts.Any(cc=>cc.IsValid)).ToList();但不起作用,这将返回所有具有有效联系人的客户并尝试以下代码,但它会引发异常 List customersResult = customers.Include(c => c.Contacts.Where(cc => cc.IsValid))。 ToList(); -
请编辑您的原始帖子以包含您尝试过的代码。请添加您的其他尝试发生的异常。
-
另外,如果
Customer是 LINQ to Entities 中的一个实体,你不能从数据库返回的内容中修改Contacts的内容,你需要一个新的对象,它不是数据库的一部分。
标签: c# entity-framework linq linq-to-sql linq-to-entities