【问题标题】:LINQ Generic SUM - VB.NETLINQ 通用 SUM - VB.NET
【发布时间】:2010-07-09 08:17:35
【问题描述】:

我有两种方法:

    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

我感觉这些可以重构为一个带有签名的方法:

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



    End Function

我来自 C# 背景,这阻碍了我弄清楚这种方法的实质。有人可以帮忙吗?

【问题讨论】:

    标签: vb.net linq-to-objects


    【解决方案1】:

    为什么不在你的“Get”语句中使用 IQueryable,

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

    并对这些函数进行查询。

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

    看看My Blog,我在你的数据访问中谈到Separating Concerns

    编辑:

    由于您的方法是GetTotalLimitGetTotalUsed,我不确定您得到的是什么“对象”。我将尝试使用我的用户类来实现它。

    保持 IQueryable 不变,在调用该方法时,您会执行类似的操作

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

    【讨论】:

    • 我很难看到这如何适用于我的情况。也许这是那些星期五的时刻之一,但你介意将你的解决方案应用到我的问题上吗?干杯。
    • 不错 - 这是星期五的时刻。
    【解决方案2】:

    您提出的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很生锈,如果我犯了错误,请纠正我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 2012-01-29
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多