views:

271

answers:

1

Suppose i have a structure

Widget

  • id
  • name

and a structure called

WidgetVoteCount

  • widgetId (FK to Widget.ID)
  • numberOfVotes

I want to display instances of Widget along with a corresponding aggregate count on my View

WIDGET-TITLE     WIDGET-COUNT(which is the sum of WidgetVoteCount.numberOfVotes)
Blue Widget       5
Purple Widget     6
etc               etc

So I create my own type that i pass into my view

Public Class WidgetWithCounts
{
    public Widget widget;
    public Int widgetCount;
}

Could someone help me with a LINQ query that i can fire off in my controller that would populate this WidgetWithCounts class? Can i accomplish this with a single query?

+3  A: 

Check out aggregate example in the LINQ 101 Samples:

http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#countSimple

This sample uses Count to return a list of customers and how many orders each has.

public void Linq76() { 
   List customers = GetCustomerList();

   var orderCounts = 
      from c in customers 
      select new {c.CustomerID, OrderCount = c.Orders.Count()};

   ObjectDumper.Write(orderCounts); 
}
Jonathan Parker