简体   繁体   English

使用LINQ和VB.NET从数据表中选择涉及多个列的条件来选择不同的行

[英]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. 我有7行数据。 The rows 1 and 2 contains columns till UnitSqcNo same. 第1行和第2行包含直到UnitSqcNo相同的列。 I want only row 3 among the two. 我只希望两者之间的第3行。 In general I want select all the rows with distinct model, unittype, unit and rest with greater CompId . 总的来说,我想选择所有具有不同model, unittype, unit的行model, unittype, unit并选择具有更大CompId ie the table should look like 即表应该看起来像

结果表

Sorry, I have no experience in VB.Net, so I post in C#: 抱歉,我没有VB.Net的经验,所以我在C#中发布:

It seems you want to filter out double entries of UnitName and keep only those with the highest value of CompID. 似乎您想过滤出UnitName的重复条目,并仅保留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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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