2014-02-14 128 views
1

我有一个linq查询来获取来自客户和客户联系人的所有数据。 但有时我不想要所有的联系人,所以我想指定一个条件,如果这个值等于得到联系人然后运行查询。类似太..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

确切的情况是什么? – ekad

回答

1

如果我理解正确的话,你想要CustomServiceModel的某些对象有CustomerContacts,而其他的没有?然后我会那样做

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() 

如果需要使用开关,自己创建一个返回布尔值的方法,并把它改为condition短语在上面的例子中。