【问题标题】:Create a List with the common elements and count of repetition创建一个包含常见元素和重复次数的列表
【发布时间】:2021-07-28 09:41:00
【问题描述】:

我有来自 4 个不同 datagridview 的 4 个 var,我通过这样的 Linq 查询获得了一系列值:

var Sums = dataGridView1.Rows.Cast<DataGridViewRow>()
          .Where(row => row.Cells[7].Value != null)
        .GroupBy(row => row.Cells[7].Value.ToString()) //inserire colonna gruppo

        .Select(g => new { Gruppo = g.Key, Serie = g.Sum(row => Convert.ToInt32(row.Cells[1].Value)) });

所以每个 var 看起来都类似于:

Gruppo | Serie

group1 |  3
group2 |  2
group3 |  7

我想要做的是获得一个列表,其中包含多个列表的交集和每个“Gruppo”元素的重复计数。

结果一定是这样的:

Gruppo | Repetition

group1 |  2 (if is present in two lists)
group2 |  3 (if is present in three lists)
group3 |  1 (if is present in one lists)

现在我有了这段代码的共同元素:

var pp = Sums.Intersect(Sums2);

但只找到具有相同“Gruppo”和相同“Serie”的元素,所以如果“gruppo”它相等但 serie 不相等,则相交不起作用。

实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: c# linq datagridview


    【解决方案1】:

    将它们放在一起并再次使用 GroupBy 和两个属性:

    var gruppoRepetitions = Sums.Concat(Sums2).Concat(Sums3)
        .GroupBy(s => new{ s.Gruppo, s.Serie })
        .Select(g => new{ Gruppo = g.Key.Gruppo, Repetition = g.Count() });
    

    【讨论】:

    • 这段代码出现两个错误:s 未定义,System.ValueTuple'2' 类型未定义或导入
    • @Gabriele:你使用的是什么 C# 版本? s 错字已修复。如果你不能使用 ValueTuples,你可以使用匿名类型。我会改变它。完成
    • 好的,现在可以了!我只删除了 GroupBy 中的 s.Serie 以获得我需要的东西。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多