我有一个linq查询,可以从客户和客户联系人那里获取所有数据。 但有时我不想要所有联系人,所以我想指定一个条件,如果此值等于获取联系人然后运行查询。同样也是..
switch (options)
{
case CustomerOptions.DefaultContacts:
break;
}
我目前有这个linq查询
var customersToReturn = new ContentList<CustomerServiceModel>()
{
Total = customers.Total,
List = customers.List.Select(c => new CustomerServiceModel
{
Id = c.Id,
ContractorId = c.ContractorId,
CompanyName = c.CompanyName,
Active = c.Active,
Address = new Address
{
Address1 = c.Address1,
Address2 = c.Address2,
Address3 = c.Address3,
Address4 = c.Address4,
},
CustomerContacts = c.CustomersContacts.Select(a => new ContactServiceModel
{
Name = a.Name,
Telephone = a.Telephone
}).Where(e => e.IsDefault)
}).ToList()
};
有没有办法可以设定条件,还是我需要为客户重复两次,为客户和客户联系重复一次?
答案 0 :(得分:1)
如果我理解正确,您希望某些CustomServiceModel
个对象拥有CustomerContacts
,而其他对象却没有?{1}}然后我会这样做
List = customers.List.Select(c => new CustomerServiceModel
{
Id = c.Id,
ContractorId = c.ContractorId,
CompanyName = c.CompanyName,
Active = c.Active,
Address = new Address
{
Address1 = c.Address1,
Address2 = c.Address2,
Address3 = c.Address3,
Address4 = c.Address4,
},
CustomerContacts = condition ?
c.CustomersContacts.Select(a => new ContactServiceModel
{
Name = a.Name,
Telephone = a.Telephone
}).Where(e => e.IsDefault)
:null
}).ToList()
如果您需要使用switch,请创建一个返回bool的方法,并在上面的示例中将其替换为condition
短语。