如何使用 LINQ (vb.net) 找到每列的最大值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16040771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:17:05  来源:igfitidea点击:

How to find max value for each column using LINQ (vb.net)

vb.netlinqmaxmultiple-columns

提问by Pawich S.

I'm writing a code using LINQ (vb.net) to find max values for every column in data table. My data look like this:

+-----------+----------+----------+----------+
|     Date   | Value1  | Value2  | Value3  |
+-----------+----------+----------+----------+
| 1/1/2013 |        12 |         13 |         19 |
| 1/2/2013 |          9 |         20 |         17 |
| 1/3/2013 |        17 |           5 |         10 |
+-----------+----------+----------+----------+

我正在使用 LINQ (vb.net) 编写代码来查找数据表中每一列的最大值。我的数据是这样的:

+-----------+---------+---------+--------- -+
| 日期 | 值 1 | 值2 | 值3 |
+-----------+----------+----------+---------+
| 1/1/2013 | 12 | 13 | 19 |
| 1/2/2013 | 9 | 20 | 17 |
| 1/3/2013 | 17 | 5 | 10 |
+-----------+---------+----------+---------+

I want to write a code to return single data record with max value in each column from all data rows so I can bind the result with gridview:

我想编写一个代码来从所有数据行的每一列中返回具有最大值的单个数据记录,以便我可以将结果与 gridview 绑定:

+----------+----------+----------+
|   Max1   |   Max2   |   Max3  |
+----------+----------+----------+
|         17 |         20 |         19 |
+----------+----------+----------+

+----------+----------+----------+
| 最大1 | 最大2 | 最大3 |
+----------+----------+----------+
| 17 | 20 | 19 |
+----------+----------+----------+

回答by Tim Schmelter

You can use Max:

您可以使用Max

Dim rows = table.AsEnumerable()
Dim Max1 = rows.Max(Function(r) r.Field(Of Int32)("Value1"))
Dim Max2 = rows.Max(Function(r) r.Field(Of Int32)("Value2"))
Dim Max3 = rows.Max(Function(r) r.Field(Of Int32)("Value3"))

If these fields actually are strings (they should not), you have to use Int32.Parse.

如果这些字段实际上是字符串(它们不应该),则必须使用Int32.Parse.

If you need these values as datasource for the GridView, you can use a DataTablewith one row:

如果您需要这些值作为 的数据源GridView,您可以使用DataTable一行:

Dim tblSource = New DataTable()
tblSource.Columns.Add("Max1", GetType(Int32))
tblSource.Columns.Add("Max2", GetType(Int32))
tblSource.Columns.Add("Max3", GetType(Int32))
tblSource.Rows.Add(Max1, Max2, Max3)