good-to-know
good-to-know

Reputation: 742

Avoid repeating columns in DataTable?

This is my 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

It has ANNF213 three times. I want to take only the first one, and wish to omit the rest rows.

Desired Output DataTable:

ItemPartNumber        VendorName      Price
ANNF213               SAMSUNG         265.41
GDFF31D               HP              65.10
FSF2122               MICROSOFT       655.47
GDSGG32               NOKIA           250.58

So, my simple question is how to get the rows after omitting the repeating particular column values?

I've tried:

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!

Upvotes: 0

Views: 662

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

I would use Linq-To-DataTable, if you just want to keep the first:

dataTable = dataTable.AsEnumerable()
    .GroupBy(row => row.Field<string>("ItemPartNumber"))
    .Select(grp => grp.First())
    .CopyToDataTable();

If you want something more meaningful, for example keep the row with the highest price:

dataTable = dataTable.AsEnumerable()
    .GroupBy(row => row.Field<string>("ItemPartNumber"))
    .Select(grp => grp.OrderByDescending(row => row.Field<decimal>("Price")).First())
    .CopyToDataTable();

Upvotes: 1

Related Questions