Returning a COUNT of rows?

Administrator

VB.NET Forum Admin
Joined
Jun 3, 2004
Messages
1,462
Programming Experience
10+
For the LINQ guru's, is this the right/best way of getting the COUNT of rows that meet a criteria?

VB.NET:
            Dim usersInGroup = From c In dsUsers.Users _
                         Where c.GroupID = groupID
            Return usersInGroup.AsDataView.Count
 
Massi's videos show this in the following manner when running a Join:

VB.NET:
Dim matchingSuppliers = From shipper In Me.Shippers _
                               Group Join Supplier In Me.Suppliers On shipper.Region Equals Supplier.Region _
                               Into SupplierCount = Count() _
                               Select shipper.Name, SupplierCount

I have found that the .Count() operator is available right on the variable when it is returned as IEnumerable of Anon Types (usersInGroup in your case unless that's typed another way?) .

Not sure which is the "right" way either.
 
Oh, also:

http://msdn2.microsoft.com/en-us/vbasic/bb738050.aspx shows:

Count operartor
Find the number of orders for a customer
VB.NET:
Public Sub XLinq44()
    Dim doc = XDocument.Load(dataPath + "nw_Orders.xml")
    Dim query = doc...<Orders>.Where(Function(o) o.<CustomerID>.Value = "VINET")
    Console.WriteLine("Customer has {0} orders", query.Count())
End Sub
Result:
Customer has 5 orders
 
Also be aware that if no rows are found, it'll throw an exception. I've been wrnagling with that for a while. Why couldn't they have just returned NULL?
 
Back
Top