2010-01-22 69 views
0

我們如何將where條件添加到linq subselect查詢中。linq where subsection的條件

List<CallLog> callLog = CallLog.SampleData(); 
List<Contacts> contacts = Contacts.SampleData(); 


var q = from call in callLog 
     where call.Incoming == true 
     group call by call.Number into g 
     select new contacts { 
           contact.FirstName = g.FirstName, 
           contact.LastName = g.LastName, 
          Count = g.Count(), 
          Avg = g.Average(c => c.Duration) <--- WHERE c.Duration > 5, 
          Total = g.Sum(c => c.Duration) <--- WHERE c.Duration >= 60 
          }; 

我們如何添加一個 「Where條件」,如上圖所示的LINQ聲明?

回答

0

只需在您所描述的條款中添加Where方法!

Avg = g.Where(c => c.Duration > 5).Average(c => c.Duration), 
Total = g.Where(c => c.Duration >= 60).Sum(c => c.Duration) 
0

你幾乎擁有了:

var q = from call in callLog 
     where call.Incoming == true 
     group call by call.Number into g 
     select new contacts { 
       contact.FirstName = g.FirstName, 
       contact.LastName = g.LastName, 
          Count = g.Count(), 
          Avg = g.Where(c => c.Duration > 5).Average(c => c.Duration), 
          Total = g.Where(c => c.Duration >= 60).Sum(c => c.Duration) 
      };