【发布时间】:2019-06-13 23:31:53
【问题描述】:
我有一个 匿名类型的IEnumerable 作为 LINQ 连接操作的结果。该列表的一些值是:
{ CellId = 0, CellIndex = "1", CellDataType = "String", CellValue = "Id", RowNumber = 0 }
{ CellId = 1, CellIndex = "2", CellDataType = "String", CellValue = "first_name", RowNumber = 0 }
{ CellId = 2, CellIndex = "3", CellDataType = "String", CellValue = "age", RowNumber = 0 }
{ CellId = 3, CellIndex = "4", CellDataType = "String", CellValue = "child_name", RowNumber = 0 }
{ CellId = 4, CellIndex = "5", CellDataType = "String", CellValue = "child_age", RowNumber = 0 }
{ CellId = 5, CellIndex = "1", CellDataType = "Number", CellValue = "1", RowNumber = 1 }
{ CellId = 6, CellIndex = "2", CellDataType = "String", CellValue = "john", RowNumber = 1 }
.
.
.
(数据来自excel表格)你可以看到rowNumber = 0的对象有表格的列名。
从电子表格中您可以注意到 John (id=1) 有 3 个孩子,所以我想按 id 分组并有类似的内容:
Id = 1
first_name = "john", age = 30, child_name = "Andy", child_age = 4
first_name = "john", age = 30, child_name = "Anna", child_age = 6
first_name = "john", age = 30, child_name = "Lily", child_age = 8
Id = 2
first_name = "Emily", age = 32, child_name = "Harry", child_age = 3
first_name = "Emily", age = 32, child_name = "David", child_age = 3
Id = 3
first_name = "Peter", age = 40, child_name = "Carol", child_age = 2
我认为 Linq GroupBy 可以做到这一点。问题是:
列表的元素是anonymous 类型,其属性是通用对象。 CellId、CellIndex、RowNumber 将始终是整数,因此我可以使用强制转换,但未定义 CellValue,它可以是字符串、整数等。
我可以生成IEnumerable of Anonymous Type <int, int, string, string, int>。我基本上是将 CellId 转换为 int,将 CellIndex 转换为 int,将 CellValue 转换为 string,将 CellDataType 转换为 string,将 RowNumber 转换为 int。但我仍然不确定如何进行分组。
如何将它们分组?
要比较 Id 是否相等,我需要查找 CellIndex = 1(对应于列名 Id),然后使用 CellValue 属性(相同的匿名类型元素)查看如果相等。
基本上我需要按 CellValue 分组,但只针对 CellIndex = 1 的那些。
有什么建议吗?
【问题讨论】:
-
如果不实现
IEqualityComparer<Something>,就无法拥有相等比较器。Something不能是匿名类型。您需要将该匿名类型映射到某个已定义的类型。 -
为什么不直接定义一个类型呢?看起来你在浪费很多时间试图让匿名类型工作,而写一个课程需要五分钟......
标签: c# .net linq anonymous-types iequalitycomparer