linq where subselect的条件

时间:2010-01-22 01:15:23

标签: linq conditional-statements where

我们如何在linq子选择查询中添加where条件。

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
                            };

如何在LINQ语句中添加“Where condition”,如上所示?

2 个答案:

答案 0 :(得分:0)

只需使用您描述的子句添加Where方法即可!

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

答案 1 :(得分: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 )
            };