我有一个包含以下详细信息的数据表。
ID | VERSION | ENTITY
1 | 01 | A01
1 | 01 | A02
2 | 01 | A01
2 | 01 | A02
我想合并列 ENTITY 的值,如下所示。
ID | VERSION | ENTITY
1 | 01 | A01/A02
2 | 01 | A01/A02
有什么方法可以使用 Linq 实现吗?
您可以使用匿名类型按多个属性分组:
var result = list1.GroupBy(x=> new {x.ID, x.VERSION}).Select(
item => new Example
{
ID = item.Key.ID,
VERSION = item.Key.VERSION,
ENTITY = string.Join("/", item.Select(c=>c.ENTITY))
});
然后选择适当的属性并将它们提供给您需要的类型的新对象。
输出:
编辑:
在 DataTable
中,您需要通过 [ ]
运算符访问列,但分组的原则保持不变:
示例数据表:
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("VERSION", typeof(string));
table.Columns.Add("ENTITY", typeof(string));
table.Rows.Add(1, "01", "A01");
table.Rows.Add(1, "01", "A02");
table.Rows.Add(2, "01", "A01");
table.Rows.Add(2, "01", "A02");
分组:
var result = table.AsEnumerable().GroupBy(x => new { ID = x["ID"], VERSION = x["VERSION"]}).Select(
item => new Example
{
ID = (int)item.Key.ID,
VERSION = (string)item.Key.VERSION,
ENTITY = string.Join("/", item.Select(c => c["ENTITY"]))
});