I'm new to Linq and was wondering how I would go about obtaining a List of Customer Id, and a count of their transactions
public class Transaction
{
public int TransactionId {get; set;}
public int CustomerId {get; set;}
}
public class Customer
{
public int ID {get; set;}
public string Name {get; set;}
public string Surname {get; set;}
}
I think I need to join customers with transactions but not too sure how I would get the count.
var query = (from c in customers
join t in transactions on c.ID equals t.CustomerId
saj's answer will only work if every customer has a transaction. Instead, it would be better to use a group join starting with Customer
, and count the result:
var query = from customer in customers
join transaction in transactions
on customer.Id equals transaction.CustomerId
into customerTransactions
select new { customer.Id, Count = customerTransactions.Count() };
See more on this question at Stackoverflow