LINQ Generic SUM - VB.NET

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 they can be reorganized into one method with a signature:

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



    End Function

I come from the background of C #, which prevents me from understanding the meat of this method. Who can help?

+3
source share
2 answers

Why not use IQueryable in the 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 complete your requests for these features.

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

Check out My Blog , where I talk about Sharing Issues in your data access.

EDIT:

Since your methods GetTotalLimitand GetTotalUsed, I'm not sure what "objects" you get. I will try and roof using my user class.

IQueryable , -

Dim TotalLimitUsers = UserRepository.GetUsers().Sum(Function(u) u.Limit)
Dim TotalUsedUsers = UserRepository.GetUsers().Sum(Function(u) u.Used)
+4

GetTotal .Net Sum. entity.Collection.Sum(Function(c) c.Limit), :

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

VB , , .

0

Source: https://habr.com/ru/post/1753850/


All Articles