VB.NET LINQ To DataTable选择Where子句

时间:2016-04-14 18:45:34

标签: vb.net linq datatable

这是我存储在名为dt:

的数据表变量中的数据表
Dim dt As New DataTable
+---------+--------+---------------+
| Carrier | AVGTAT |     Name      |
+---------+--------+---------------+
| ABCD    |   2078 | Term Check    |
| ABCD    |      0 | AdHoc         |
| ABCD    |  26406 | Cash on Term  |
| REWS    |   7358 | Failed Bill   |
| ZELT    |  11585 | BL150         |

我需要使用LINQ to DataTable获取AVGTAT列的值,其中Carrier =“x”和Name =“X”

我该如何实现?

谢谢!

1 个答案:

答案 0 :(得分:1)

这是C#版本。

var avg = (from t1 in dt.AsEnumerable()
                select new
                {
                    Carrier = t1.Field<string>("Carrier"),
                    Name = t1.Field<string>("Name"),
                    Avg = t1.Field<int>("AVGTAT")

                }).Where(s => s.Carrier == "X" && s.Name == "X")
                                                      .Select(v=>v.Avg).FirstOrDefault();

和VB.NET版本

Dim avg = dt.AsEnumerable().[Select](Function(x) New With {
       Key .Carrier = x.Field(Of String)("Carrier"),
       Key .Name = x.Field(Of String)("Name"),
       Key .Avg = x.Field(Of Int32)("Level")
   }).Where(Function(s) s.Carrier = "X" AndAlso s.Name = "X")
                                            .[Select](Function(h) h.Avg).FirstOrDefault()