避免在 DataTable 中重复列?
Avoid repeating columns in DataTable?
这是我的数据表:
ItemPartNumber VendorName Price
ANNF213 SAMSUNG 265.41
GDFF31D HP 65.10
ANNF213 APPLE 115.51
FSF2122 MICROSOFT 655.47
GDSGG32 NOKIA 250.58
ANNF213 SAMSUNG 225.40
已经ANNF213
三次了。我只想拿第一行,并希望省略其余行。
所需的输出数据表:
ItemPartNumber VendorName Price
ANNF213 SAMSUNG 265.41
GDFF31D HP 65.10
FSF2122 MICROSOFT 655.47
GDSGG32 NOKIA 250.58
所以,我的简单问题是如何在省略重复的特定列值后获取行?
我试过:
DataView view = new DataView(dataTable);
dataTable = view.ToTable(true, "ItemPartNumber", "VendorName", "Price");
//This isn't working.
dataTable = view.ToTable(true, "ItemPartNumber");
//This is working, but only `ItemPartNumber` is there on data table, but I need all three columns. Help me in this!
如果您只想保留第一个,我会使用 Linq-To-DataTable:
dataTable = dataTable.AsEnumerable()
.GroupBy(row => row.Field<string>("ItemPartNumber"))
.Select(grp => grp.First())
.CopyToDataTable();
如果您想要更有意义的东西,例如保留价格最高的行:
dataTable = dataTable.AsEnumerable()
.GroupBy(row => row.Field<string>("ItemPartNumber"))
.Select(grp => grp.OrderByDescending(row => row.Field<decimal>("Price")).First())
.CopyToDataTable();
这是我的数据表:
ItemPartNumber VendorName Price
ANNF213 SAMSUNG 265.41
GDFF31D HP 65.10
ANNF213 APPLE 115.51
FSF2122 MICROSOFT 655.47
GDSGG32 NOKIA 250.58
ANNF213 SAMSUNG 225.40
已经ANNF213
三次了。我只想拿第一行,并希望省略其余行。
所需的输出数据表:
ItemPartNumber VendorName Price
ANNF213 SAMSUNG 265.41
GDFF31D HP 65.10
FSF2122 MICROSOFT 655.47
GDSGG32 NOKIA 250.58
所以,我的简单问题是如何在省略重复的特定列值后获取行?
我试过:
DataView view = new DataView(dataTable);
dataTable = view.ToTable(true, "ItemPartNumber", "VendorName", "Price");
//This isn't working.
dataTable = view.ToTable(true, "ItemPartNumber");
//This is working, but only `ItemPartNumber` is there on data table, but I need all three columns. Help me in this!
如果您只想保留第一个,我会使用 Linq-To-DataTable:
dataTable = dataTable.AsEnumerable()
.GroupBy(row => row.Field<string>("ItemPartNumber"))
.Select(grp => grp.First())
.CopyToDataTable();
如果您想要更有意义的东西,例如保留价格最高的行:
dataTable = dataTable.AsEnumerable()
.GroupBy(row => row.Field<string>("ItemPartNumber"))
.Select(grp => grp.OrderByDescending(row => row.Field<decimal>("Price")).First())
.CopyToDataTable();