【问题标题】:Select distinct rows from a datatable with criteria involving multiple columns using LINQ with VB.NET使用 LINQ 和 VB.NET 从数据表中选择不同的行,条件涉及多列
【发布时间】:2012-03-09 10:48:13
【问题描述】:

我有一个如图所示的数据表。

让我根据这张图片解释我的要求。我有 7 行数据。第 1 行和第 2 行包含直到 UnitSqcNo 相同的列。我只想要两者中的第 3 行。一般来说,我想选择具有不同model, unittype, unit 的所有行并以更大的CompId 休息。即表格应该看起来像

【问题讨论】:

  • For Each dr As DataRow In dtCompDetails.Rows Dim dtDistinctRows = From dRow In dtCompDetails.Rows _ Where dRow("OrgModelId") = dr("OrgModelID") _ And dRow("OrgUnitTypeID") = dr("OrgUnitTypeID") _ And dRow("OrgUnitID") = dr("OrgUnitID") _ Select dRow.Distinct() Next
  • 这张表中没有主键吗?

标签: asp.net vb.net linq


【解决方案1】:

对不起,我没有VB.Net的经验,所以我用C#发帖:

您似乎想过滤掉 UnitName 的双重条目,只保留 CompID 值最高的条目。鉴于此,您可以尝试以下方法:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多