我有以下数据表:
Article Price
ART1 99
ART2 100
ART3 150
ART2 90
ART1 50
现在,我应该用这样的重复位置创建一个新的数据表
Article Duplicates
ART1 1,5
ART2 2,4
ART3
ART2 2,4
ART1 1,5
所以关键是“文章”栏
我发现周围只有关于查找哪些是重复值以及使用 linq 重复这些值的次数的示例。
如何使用 linq 实现类似的目标?
谢谢
最佳答案
您可以使用这种方法:
var articleLookup = yourTable.AsEnumerable()
.Select((row, index) => new { Row = row, RowNum = index + 1 })
.ToLookup(x=> x.Row.Field<string>("Article"));
DataTable dupTable = new DataTable();
dupTable.Columns.Add("Article");
dupTable.Columns.Add("Duplicates");
foreach(DataRow row in yourTable.Rows)
{
DataRow addedRow = dupTable.Rows.Add();
string article = row.Field<string>("Article");
var dupRowNumList = articleLookup[article].Select(x => x.RowNum).ToList();
string dupRowNumText = dupRowNumList.Count == 1 ? "" : String.Join(",", dupRowNumList);
addedRow.SetField("Article", article);
addedRow.SetField("Duplicates", dupRowNumText);
}
关于c# - DataTable:如何获取重复项和重复项的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240010/