【问题标题】:Need to find recurring values in array between two bounds需要在两个边界之间的数组中找到重复值
【发布时间】:2017-05-09 14:25:15
【问题描述】:

我有这段代码可以在我的数组中查找重复出现的值。我有 81 个文本框形成一个网格,它们位于 9 行,每行 9 个框中。我早些时候在我的代码中将它们全部保存到一个包含 81 个元素的一维数组中。我在另一个问题上找到了其中的一些代码:Finding duplicate integers in an array and display how many times they occurred,它对我有用,但我找不到它实际上是哪个数组元素重复出现的。

int[] OrigValues = new int[];//Already defined earlier, and assigned.

for (int c = 1; c <= 9; c++) //in this case, I called my int c instead of the usual i
    {

        Console.WriteLine("Row {0}:", c);
        var dict = new Dictionary<int, int>();

        foreach (var value in OrigValues.SubArray(c * 9 -9, 9))
        {
            if (dict.ContainsKey(value))
                dict[value]++;
            else
                dict[value] = 1;       
        }                        

        foreach (var pair in dict)
        {
            Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
            if (pair.Value >= 2 && pair.Key != 0)
            {
                //I have no way of finding which 2 array slots were the ones that had the same value in each of these rows.
            }
        }

    }

OrigValues.SubArray 是一种扩展方法,它的作用类似于子字符串,除了它用于数组,从索引开始获取数组元素,并获取一个长度(那里,c* 9 - 9 是我的索引,而 9 是我的长度)

【问题讨论】:

    标签: c# arrays windows


    【解决方案1】:

    您可以将整个过程变成一个 LINQ 查询:

    var duplicates =
        OrigValues
            .Select((value, index) => new
                {
                    Coordinate = index,
                    Value = value
                })
            .GroupBy(tuple => tuple.Value)
            .Where(group => group.Count() > 1)
            .ToList();
    
    foreach (var group in duplicates)
    {
        Console.Write($"{group.Key} appears in");
        foreach (var tuple in group)
            Console.Write($" {tuple.Coordinate}");
        Console.WriteLine();
    }
    

    【讨论】:

    • 我希望它返回 1-81 的值,而不是坐标。所以我不想在控制台中写 (3 6),而是写 29
    • @ThatGuy 将代码更改为仅打印包含重复值的数组索引。
    • 感谢您对此的回复,但出现错误:“无法在 foreach 中将类型 '' 转换为 'int'”(var group in duplicates)
    • @ThatGuy 是的,对不起,我忘了里面是匿名类型。
    • 仍然有问题...抱歉,我以前从未使用过 LINQ。
    猜你喜欢
    • 2012-01-12
    • 2023-03-26
    • 2020-09-08
    • 2022-08-02
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    相关资源
    最近更新 更多