LINQ on datatable汇总多列vb.net

时间:2018-06-11 22:16:40

标签: vb.net linq datagridview datatable sum

是否有人知道是否可以根据另一列的给定条件对数据表或数据视图的多列进行求和?简而言之,我有一个看起来像这样的表:

Ph Length  Start
A     10     1.5
B     14     2
C     9      1.8
A     11     1.4

依旧......

我想要做的是理解的是,在一个查询中,是否可以使用LINQ对“长度”和“开始”列的“Ph”进行求和?或者我是否需要为每封信写一个?

基本上结果需要是A = 21,2.9。 B = 14,2。C = 9,1.8

我很难过,老实说我不知道​​怎么做。我甚至不介意有人能指出我更好地学习LINQ的资源。

1 个答案:

答案 0 :(得分:1)

要根据键列值合并LINQ中的行,请使用steve@steve.com

获得行组后,您可以对感兴趣的列求和。

在LINQ查询理解语法中,

    function test1() {
      var testemail = ["Steve<steve@steve.com>","displayname<display@steve.com>"];
  var debug = stripEmail(testemail);

      var debug9 = "";
    }

function stripEmail(email) {
  //Give me an email with a display name and I will strip out the display name
  //"<Steve Gon> stevegon@google.com"
  if (typeof email === 'string') {
    var arr = [email];
  } else {
    var arr = email;
  }

  for (i=0; i<arr.length; i++) {
    if (arr[i].search("<")>-1) {//If there is no less than, then it doesn't have a display name
      var part1 = arr[i].split("<");
      if (part1.length == 2) {
        arr[i] = part1[1].replace(">","");
        arr[i] = arr[i].replace("<","");
        arr[i] = arr[i].replace(" ","");
      } 
    } 
  }
  return arr;
}

如果您更喜欢lambda语法,

GroupBy

在这两种情况下,查询结果都是我在Dim sums = From dr In dt.AsEnumerable() Group dr By Ph = dr.Field(Of String)("Ph") Into drg = Group Select New With { .Ph = Ph, .LengthSum = drg.Sum(Function(dr) dr.Field(Of int)("Length")), .StartSum = drg.Sum(Function(dr) dr.Field(Of Double)("Start")) } / Dim sums2 = dt.AsEnumerable() _ .GroupBy(Function(dr) dr.Field(Of String)("Ph")) _ .Select(Function(drg) New With { .Ph = drg.Key, .LengthSum = drg.Sum(Function(dr) dr.Field(Of Integer)("Length")), .StartSum = drg.Sum(Function(dr) dr.Field(Of Double)("Start")) }) 中创建的匿名对象的IEnumerable。您可以创建一个类,或者通过一些额外的工作,创建一个新的select来保存答案,或者使用现有Select的克隆。