从数据表中获取每个不同值的重复项计数

发布于 2024-09-13 12:28:34 字数 197 浏览 1 评论 0原文

我有一个数据表,其中有一个文本列“标题”,它可以有多个重复值。我可以使用数据视图删除重复项。

DataView v = new DataView(tempTable);
tempTable = v.ToTable(true, "Title");

但是我怎样才能在没有任何循环的情况下获得每个不同值的重复项数量呢?

I've a datatable which has a single text column 'Title' which can have multiple values with duplicates. I can remove the duplicates using a dataview.

DataView v = new DataView(tempTable);
tempTable = v.ToTable(true, "Title");

But how can i get the number of duplicates for each distinct value without any looping?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我ぃ本無心為│何有愛 2024-09-20 12:28:34

如果您不想循环或使用 Linq,则无法做到这一点,但您可以在数据表上使用计算列,并附加一个条件(如果适用)。也就是说,数据应该位于这样的两个相关表中。

DataRelation rel = new DataRelation("CustToOrders", data.Tables["Customers"].Columns["customerid"],    data.Tables["Orders"].Columns["customerid"]);
data.Relations.Add(rel);

鉴于 customerid 字段作为 Orders 表中的外键,因此它有重复项。
您可以通过以下方式获取重复项的计数:

data.Tables["Customers"].Columns.Add("Duplicates",
   GetType(Decimal), "Count(child.customerid)");

If you don't want to loop or use Linq, so there is no way to do that but you can use a computed column on the data table with one more condition if applicable with you. That is the data should be in two related tables like this.

DataRelation rel = new DataRelation("CustToOrders", data.Tables["Customers"].Columns["customerid"],    data.Tables["Orders"].Columns["customerid"]);
data.Relations.Add(rel);

Given that customerid field as a Foreign key in the Orders table so it has duplicates.
You can get the count of the duplicates this way:

data.Tables["Customers"].Columns.Add("Duplicates",
   GetType(Decimal), "Count(child.customerid)");
Oo萌小芽oO 2024-09-20 12:28:34

我得到你想要的结果的方式看起来像这样:

tempTable.Rows.Cast<DataRow>()
    .Select(dr => Convert.ToString(dr[0]))
    .GroupBy(dr => dr)
    .Select(g => new { Title = g.Key, Count = g.Count() });

然而,它实际上是在幕后循环的。事实上,我想不出一种方法可以在不检查每条记录的情况下进行这种分组。

缺点是该表达式的结果是一系列匿名类型实例。如果您仍然希望结果是 DataView,则可以重写最后一个 Select 以创建一个包含两列的新 DataRow,并将它们推送到传递给 DataView 的新 DataTable 中。

The way I would get the results that you want would look something like this:

tempTable.Rows.Cast<DataRow>()
    .Select(dr => Convert.ToString(dr[0]))
    .GroupBy(dr => dr)
    .Select(g => new { Title = g.Key, Count = g.Count() });

However, it's actually looping under the hood. In fact, I can't think of a way to do that kind of a grouping without inspecting each record.

The drawback is that the result of that expression is a sequence of anonymous type instances. If you still want the result to be a DataView, you could rewrite the last Select to create a new DataRow with two columns, and shove them into a new DataTable which you pass to the DataView.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文