您好,我有一個List<Tuple<int, int>>
,我想檢查是否有重復的元素,無論順序如何。因此,例如,如果我的串列包含
List<Tuple<int, int>> tuple = new List<Tuple<int, int>>()
{
new Tuple<int, int>(1, 2),
new Tuple<int, int>(2, 1),
new Tuple<int, int>(3, 2)
};
我想洗掉第二項,因為它包含與第一項相同的元素,但順序相反 (1,2) 和 (2,1)。
最有效的方法是什么?
uj5u.com熱心網友回復:
var set = new HashSet<long>();
var unique = tuple.Where(t => set.Add((long)Math.Max(t.Item1, t.Item2) << 32 | Math.Min(t.Item1, t.Item2)))
如果您沒有迭代一次.ToList()
,請在最后添加
更新
從原始串列中洗掉
var set = new HashSet<long>();
for (int i = tuple.Count -1; i >= 0; i--)
{
if (!set.Add((long)Math.Max(t.Item1, t.Item2) << 32 | Math.Min(t.Item1, t.Item2)))
tuple.RemoveAt(i);
}
uj5u.com熱心網友回復:
您可以使用DistinctBy
功能:
var withoutDuplicates = tuple
.DistinctBy(t => Tuple.Create(Math.Min(t.Item1, t.Item2), Math.Max(t.Item1, t.Item2)))
.ToList();
uj5u.com熱心網友回復:
你可以定義一個IEqualityComparer
然后你就可以使用Linq 的Distinct
功能:
var withoutDuplicate = tuple.Distinct(new IntegerTupleComparer()).ToList();
這是一個天真的實作IEqualityComparer<Tuple<int, int>>
public class IntegerTupleComparer: IEqualityComparer<Tuple<int, int>>
{
public bool Equals(Tuple<int, int> lhs, Tuple<int, int> rhs)
{
if (lhs == null && rhs == null)
return true;
if (lhs == null || rhs == null)
return false;
return GetHashCode(rhs).Equals(GetHashCode(lhs));
}
public int GetHashCode(Tuple<int, int> _)
=> _.Item1.GetHashCode() _.Item2.GetHashCode();
}
dotnet fiddle 上的作業示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/531098.html
標籤:C#实体框架林克元组