You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中IEquatable<T>实现大小写不敏感字段匹配及DataGridView行合并

问题分析与修改方案

你的IEquatable<Product>实现核心问题是字符串字段的大小写敏感比较,这会导致仅大小写不同的Name/Code被判定为不同对象,无法实现合并行的需求。

当前代码的问题点

当前代码中Code = other.Code和Name = other.Name是严格的大小写敏感比较,比如"Apple"和"apple"会被视为不相等,不符合你要合并大小写不同但实际是同一产品的需求。

修改后的Equals方法

将字符串字段的比较改为不区分大小写,日期字段本身是值类型,直接比较即可:

Public Overloads Function Equals(ByVal other As Product) As Boolean Implements IEquatable(Of Product).Equals
    If Object.ReferenceEquals(other, Nothing) Then
        Return False
    End If

    If Object.ReferenceEquals(Me, other) Then
        Return True
    End If

    If Me.GetType() IsNot other.GetType() Then
        Return False
    End If

    ' 字符串字段使用不区分大小写比较,日期字段直接比较
    Return [Date] = other.Date _
           AndAlso String.Equals(Code, other.Code, StringComparison.OrdinalIgnoreCase) _
           AndAlso String.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
End Function

必须补充的GetHashCode重写

实现IEquatable<T>时,必须同步重写GetHashCode,保证相等的对象返回相同的哈希值,否则分组、去重等依赖哈希的操作会出错:

Public Overrides Function GetHashCode() As Integer
    ' 结合日期哈希值,以及字符串的不区分大小写哈希值
    Dim hash = [Date].GetHashCode()
    hash = hash Xor (If(Code Is Nothing, 0, StringComparer.OrdinalIgnoreCase.GetHashCode(Code)))
    hash = hash Xor (If(Name Is Nothing, 0, StringComparer.OrdinalIgnoreCase.GetHashCode(Name)))
    Return hash
End Function

合并行的示例逻辑(参考)

修改完相等判定后,你可以用Linq分组来合并数量:

' 假设products是你的Product集合
Dim mergedProducts = products.GroupBy(Function(p) p) _
                             .Select(Function(g) New Product With {
                                         .Date = g.Key.Date,
                                         .Code = g.Key.Code,
                                         .Name = g.Key.Name,
                                         .Quantity = g.Sum(Function(p) p.Quantity)
                                     })
' 将合并后的集合绑定到DataGridView
DataGridView1.DataSource = mergedProducts.ToList()

内容的提问来源于stack exchange,提问作者user22468841

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 08:40:19