简体   繁体   中英

Select distinct rows from a datatable with criteria involving multiple columns using LINQ with VB.NET

I have a datatable as shown in the figure.

初始表

Let me explain my required based on this image. I have 7 rows of data. The rows 1 and 2 contains columns till UnitSqcNo same. I want only row 3 among the two. In general I want select all the rows with distinct model, unittype, unit and rest with greater CompId . ie the table should look like

结果表

Sorry, I have no experience in VB.Net, so I post in C#:

It seems you want to filter out double entries of UnitName and keep only those with the highest value of CompID. Given that, you could try the following:

DataTable dt = GetDataTable(); //your logic of building your data table

//order rows by CompID, group by UnitName and keep only first entry of each group        
var filteredData = (from row in dt.AsEnumerable() orderby row.Field<int>("CompID") descending group row by row.Field<string>("UnitName")).Select(r => r.First());

DataTable nt = GetDataTable(); //alternatively, you could build a new data table
nt.Rows.Clear();  //clear table as it is used as destination for filtered data

foreach (DataRow r in filteredData)  //add filtered rows to table
{
     DataRow n = nt.NewRow();
     n.ItemArray = r.ItemArray;
      nt.Rows.Add(n);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM