views:

111

answers:

2

how can we add a where condition to a linq subselect query.

i.e.

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

How can we add a "Where condition" to the LINQ statement as shown above?

A: 

Simply add a Where method with the clause you described!

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

You almost had it:

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 )
            };
Craig Stuntz