如果我有 2 個int陣列 a 和 b 并且它們包含這樣的資料..
a[0] = 1
a[1] = 3
a[2] = 7
b[0] = 6
b[1] = 3
b[2] = 5
如何檢查所有數字對是否都是唯一的,例如,同一索引處的每個組合a[i]在b[i]陣列的其余部分中都不會重復......所以上面的資料會通過,但如果我在下面介紹它會失敗。 .
a[24] = 7
b[24] = 5
因為這個組合已經存在于索引 2 的陣列中。我可以在 LINQ 中執行此操作嗎?
uj5u.com熱心網友回復:
如果兩個陣列上的對中值的順序很重要(即被a[0] == 1, b[0] == 2認為與 不同a[0] == 2, b[0] == 1),那么使用 Linq 檢查唯一性的一種方法如下:
bool unique = a.Zip(b).Distinct().Count() == a.Length;
如果對中值的順序不重要,則稍微復雜一些:
bool unique = a.Zip(b).DistinctBy(
x => (Math.Min(x.First, x.Second), Math.Max(x.First,x.Second)))
.Count() == a.Length;
這些解決方案假定其中一個陣列中的缺失值將被忽略。
(注意:DistinctBy()僅在 .Net 6.0 或更高版本中可用,或通過 NuGet 包提供。)
uj5u.com熱心網友回復:
我設法解決了這個問題并解決了這個問題:
a.Zip(b, (aPos, bPos) => new { aPosition = aPos, bPosition = bPos }).Distinct().Count()
這將告訴我在同一個索引中有多少不同的兩個值集,所以我可以從這里解決剩下的問題。
如果我的問題不清楚,請道歉。
uj5u.com熱心網友回復:
試試這個樣本:
int [] aa = a.Distinct().ToArray();
要么 :
public static bool HasDuplicates<T>(IList<T> items)
{
Dictionary<T, bool> map = new Dictionary<T, bool>();
for (int i = 0; i < items.Count; i )
{
if (map.ContainsKey(items[i]))
{
return true; // has duplicates
}
map.Add(items[i], true);
}
return false; // no duplicates
}
并致電:
string[] strings = new[] { "1", "2", "3" };
Utility.HasDuplicates(strings)// this will return false
int[] items=new []{1,2,3,1};
Utility.HasDuplicates(items)// this will return true
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429099.html
