需要在两个边界之间找到数组中的重复值

时间:2016-12-23 23:31:12

标签: c# arrays windows

我有这个代码来查找我的数组中的重复值。我有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是我的长度)

1 个答案:

答案 0 :(得分:0)

您可以将整个过程转换为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();
}