我需要返回所有具有有效联系方式的客户:
联系方式:
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 Contacts Displays无联系人的主干,LINQ如何做到这一点?
答案 0 :(得分:0)
List<Customer> customersResult = customers.Select(x => new Customer {
ID = x.ID,
Name = x.Name,
Contacts = x.Contacts?.Where(c => c.IsValid).ToList()
}).ToList();