【发布时间】:2013-06-03 19:31:45
【问题描述】:
我有一个表格(从 SQL 数据库中检索的数据),格式为:
╔═══════╦══════════════╗
║ Model ║ Manufacturer ║
╠═══════╬══════════════╣
║ A ║ 1 ║
║----------------------║
║ A ║ 2 ║
║----------------------║
║ A ║ 3 ║
║----------------------║
║ B ║ 4 ║
║----------------------║
║ B ║ 5 ║
║----------------------║
║ C ║ 6 ║
║----------------------║
║ D ║ 7 ║
║----------------------║
║ D ║ 8 ║
║----------------------║
║ D ║ 9 ║
║----------------------║
║ D ║ 10 ║
╚═══════╩══════════════╝
当我将数据绑定到<asp:datagrid> 时,每一行都是它自己的<tr>。不过,我需要的是:
╔═══════╦══════════════╗
║ Model ║ Manufacturer ║
╠═══════╬══════════════╣
║ A ║ 1 ║
║ ║ 2 ║
║ ║ 3 ║
║----------------------║
║ B ║ 4 ║
║ ║ 5 ║
║----------------------║
║ C ║ 6 ║
║----------------------║
║ D ║ 7 ║
║ ║ 8 ║
║ ║ 9 ║
║ ║ 10 ║
╚═══════╩══════════════╝
我花了很多时间搜索并尝试了许多不同的东西,其中大部分使用 LINQ。但是我对LINQ的了解和了解很少。我认为(但我可能完全错了),我最接近的来自这个问题/答案:Linq query to combine cell results?。我稍作修改的版本是:
Dim results = table.AsEnumerable().GroupBy(Function(x) x.Field(Of String)("Model")).[Select](Function(grouping) New With {
.Key = grouping.Key,
.CombinedModel = grouping.Aggregate(Function(a, b) a + " " + b)
}).[Select](Function(x) New ModelRecord() With {
.Manufacturer = x.Key.Manufacturer,
.Model = x.CombinedModel
})
但是由于我缺乏 LINQ 知识,我不明白“定义一个具体类型来表示 Row”(这会在我的代码中与 ModelRecord() 产生问题)。
在这一点上,我几乎完全迷失了。我是不是把事情复杂化了?完全错了吗?非常感谢这里的任何帮助。
【问题讨论】:
-
Yuriy,这正是我想要做的。我正在尝试使用该代码(针对我的数据表中的列名进行了修改),但出现错误:
Argument not specified for parameter 'index' of Public ReadOnly Default Property Chars(index As Integer) As Char -
能否请您发布您修改后的代码并指出错误发生的位置?
-
From oRow In table Group By Manufacturer = oRow.Field(Of String)("Manufacturer") Into Group Select Manufacturer, Model = _ Group.Aggregate(Of StringBuilder)(New StringBuilder, Function(Current As StringBuilder, row As DataRow) _ Current.AppendFormat(",{0}", row.Field(Of String)("Model"))).ToString.Substring(1)()错误是Select Manufacturer, Model =部分之后的所有内容(也就是说,Visual Studio 会在之后的所有内容下划线)。 -
为什么要在
ToString.Substring(1)后面加上()?