3 回答

TA貢獻1878條經驗 獲得超4個贊
你可以試試HashSet<int>,例如
int[,] arr = new int[3, 3] {
{1, 2, 6 },
{4, 1, 5 },
{6, 1, 8 }
};
HashSet<int> unique = new HashSet<int>();
foreach (var item in arr)
if (!unique.Add(item))
Console.WriteLine(item); // Not unique, print it out
結果:
1
6
1
如果我們想打印每個副本一次,我們可以添加另一個HashSet<int>:
HashSet<int> unique = new HashSet<int>();
HashSet<int> duplicates = new HashSet<int>();
foreach (var item in arr)
if (!unique.Add(item))
duplicates.Add(item);
foreach (var item in duplicates)
Console.WriteLine(item);
最后,如果您想計算重復出現的次數,我們可以更改HashSet<int> duplicates為Dictionary<int, int> duplicates:
HashSet<int> unique = new HashSet<int>();
Dictionary<int, int> duplicates = new Dictionary<int, int>();
foreach (var item in arr)
if (!unique.Add(item))
if (duplicates.TryGetValue(item, out int count))
duplicates[item] = count + 1;
else
duplicates[item] = 2;
foreach (var item in duplicates)
Console.WriteLine($"{item.Key} appears {item.Value} times");
編輯:您可以將foreach循環更改為嵌套 for循環,例如:
所有重復項
for (int i = 0; i < arr.GetLength(0); ++i)
for (int j = 0; j < arr.GetLength(1); ++j)
if (!unique.Add(arr[i, j]))
Console.WriteLine(arr[i, j]);
Distinct duplicates
HashSet<int> duplicates = new HashSet<int>();
for (int i = 0; i < arr.GetLength(0); ++i)
for (int j = 0; j < arr.GetLength(1); ++j)
if (!unique.Add(arr[i, j]))
if (duplicates.Add(arr[i, j])) // print distinct duplicate only
Console.WriteLine(arr[i, j]);

TA貢獻1817條經驗 獲得超14個贊
或許是這樣的:
var arr = new int[3, 3]{{1,2,6}, {4,1,5}, {6,1,8}}; var duplicates = arr .Cast<int>() .GroupBy(n => n) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToArray();
.Cast<int>()
使數組可用于 LINQ,.GroupBy(n => n)
按值對數字進行分組,.Where(g => g.Count() > 1)
計算組中的項目數,.Select(g => g.Key)
僅返回組鍵 - 原始值。
.Where(g => g.Count() > 1).Select(g => g.Count())
返回每個的計數,或者根據需要對組進行操作。

TA貢獻1909條經驗 獲得超7個贊
效率不高,但您也可以將計數存儲在字典中,然后打印計數大于 1 的鍵:
var counts = new Dictionary<int, int>();
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
var number = arr[i, j];
if (!counts.ContainsKey(number))
{
counts[number] = 0;
}
counts[number] += 1;
}
}
foreach (var pair in counts)
{
if (pair.Value > 1)
{
Console.WriteLine(pair.Key);
}
}
// 1
// 6
- 3 回答
- 0 關注
- 205 瀏覽
添加回答
舉報