How to select Values from Datatable which appears once

myDataTable has a column named ORDER_NO. I would like to select the rows from this table which appears once. If a value appears two times than it should not selected. ORDER_NO contain Values

1000A
1001A
1001B
1002A
1002B
1002C
1000A
1001A
1001B

I want to select only form the values above are:

1002A
1002B
1002C

as they appears once in the column. Can anyone help?

Upvotes: 0

Views: 75

Answers (2)

Nikhil Gaur
Nikhil Gaur

Reputation: 1272

Apart from @Tim's answer you can also use DataView to simplify this thing

DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "ORDER_NO");

I think this is the simplest way to get distinct values from any table. You can even mention multiple columns in the ToTable method. Just pass column name as argument like ORDER_NO is send in above sample code.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460038

So you want only unique rows according to the ORDER_NO column?

Presuming that it's a string column you could use LINQ's Enumerable.GroupBy:

var uniqueRows = table.AsEnumerable()
    .GroupBy(row => row.Field<string>("ORDER_NO"))
    .Where(group => group.Count() == 1)
    .Select(group => group.First());

if you want a new DataTable from the unique rows you can use:

table = uniqueRows.CopyToDataTable();

If you instead only want this column's values:

IEnumerable<string> unqiueOrderNumbers = uniqueRows.Select(row => row.Field<string>("ORDER_NO"));

Upvotes: 2

Related Questions