如何在vb.net中总结结构数组的相似元素? [英] How to sum similar element of an array of structure in vb.net?

查看:21
本文介绍了如何在vb.net中总结结构数组的相似元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构数组:

Public Structure emp
    Public empName As String
    Public empAge As Int32
    Public empsal As Int32 ' salary
End Structure

具有 30 个元素的上述结构的数组.我想对 emp.empName & 的那些 emp 元素的 empsal 求和emp.empAge 是相等的.

An array of the above structure with 30 element. I want to sum the empsal of those emp elements whose emp.empName & emp.empAge is equal.

例如

emp(0).empName = "test"
emp(0).empAge = 32
emp(0).empsal = 10000

emp(1).empName = "test"
emp(1).empAge = 32
emp(1).empsal = 10000

emp(2).empName = "test12"
emp(2).empAge = 32
emp(2).empsal = 10000

如何才能使结果为 (test,20000) 和 (test12,10000)?

使用 .NET 3.5

Using .NET 3.5

推荐答案

编辑样本以在键中包含年龄,并以 emp 数组结束.

Edited the samples to include the age in the key, and to end up with an emp array.

绝对的.为此,您应该查看 LINQ - 您基本上希望按姓名和年龄分组,然后求和工资.在 C# 中,您可以编写如下代码:

Absolutely. You should look at LINQ for this - you basically want to group by name and age, and then sum the salary. In C# you'd write something like:

var query = employees.GroupBy
     (x => new { x.empName, x.empAge },
      x => x.empSal,
      (key, salaries) => new emp { empName = key.empName,
                                   empAge = key.empAge,
                                   empSalary = salaries.Sum() })
var array = query.ToArray();

认为在 VB 中应该是这样的:

I think in VB this would be something like:

Dim query = employees.GroupBy( _
    Function(x) New With { Key .Name = x.empName, Key .Age = x.empAge }, _
    Function(x) x.empSal, _
    Function(k, salaries) New Emp With _
         { .empName = k.Name, .empAge = k.Age, .empSalary = salaries.Sum() }_
    )
Dim array = query.ToArray()

请参阅 GroupBy 文档 了解更多详情.

See the GroupBy documentation for more details.

顺便说一句,我建议:

  • 根据 .NET 命名约定为您的类型提供更完整的名称
  • 使它成为一个类而不是一个结构(它不是一个真正的单一值,如 int)
  • 使用属性代替公共字段
  • 从字段/属性中删除 emp 前缀 - 毕竟它们已经是员工类型的一部分
  • Giving your type a fuller name which follows .NET naming conventions
  • Making it a class rather than a structure (it's not really a single value, like an int)
  • Using properties instead of public fields
  • Removing the emp prefix from the fields/properties - they're already part of an employee type, after all

这篇关于如何在vb.net中总结结构数组的相似元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆