views:

36

answers:

2

Hi,

I have two methods:

    Public Function GetTotalLimit(ByVal entity As Entity) As Int64

        Return (From c In entity.Collection
                Select c.Limit).Sum()

    End Function

    Public Function GetTotalUsed(ByVal entity As Entity) As Int64

        Return (From c In entity.Collection
                Select c.Used).Sum()

    End Function

I have a feeling that these can be refactored to one single method with the signature:

    Public Function GetTotal(Of TKey)(ByVal entity As Entity, ByVal field As Func(Of CollectionType, TKey)) As Int64



    End Function

I come from a C# background which is hindering me to figure out the meat of this method. Anyone can help?

+2  A: 

Why not use IQueryable on your "Get" Statement,

    Public Function GetUsers() As IQueryable(Of User) Implements IUserRepository.GetUsers 
        Dim users = (From u In dc.Users 
                    Select u) 
        Return users.
   End Function

and do your queries on those Functions.

Dim GetUser As User = UserRepository.GetUsers().Where(Function(u) (u.ID = id)).SingleOrDefault 
Return GetUser

Have a look at My Blog where I talk about Separating Concerns in your Data Access.

EDIT:

Since your methods are GetTotalLimit and GetTotalUsed, I'm not sure what "objects" you're getting. I'll try and wing it using my user class.

Keep the IQueryable the same, and in your call to the method you would do something like

Dim TotalLimitUsers = UserRepository.GetUsers().Sum(Function(u) u.Limit)
Dim TotalUsedUsers = UserRepository.GetUsers().Sum(Function(u) u.Used)
rockinthesixstring
I am struggling to see how this applies to my situation. Maybe it is one of those Friday moments but would you mind applying your solution to my problem? Cheers.
youwhut
I've edited my answer.
rockinthesixstring
Nice one - it was a Friday moment.
youwhut
A: 

Your proposed GetTotal function already exists in .Net, and is just an overload of Sum. You would call it like entity.Collection.Sum(Function(c) c.Limit), or to use your example:

Public Function GetTotalLimit(ByVal entity As Entity) As Int64 
    Return entity.Collection.Sum(Function(c) c.Limit)
End Function 

Public Function GetTotalUsed(ByVal entity As Entity) As Int64 
    Return entity.Collection.Sum(Function(c) c.Used)
End Function

My VB is pretty rusty, so correct me if I made a mistake.

Gabe