我有一個列表包含一堆基於x和y位置的位置,我正在取兩個位置的區別。所以,例如我有像(0,1),(1,0)和(1,2),(2,1)和(2,3),(3,2)這樣的重複。我想從我的列表中刪除所有這些重複項目以實現我的目標。是否有捷徑可尋?我一直在試圖建立一個算法,但它很難。因爲我已經得到了像90點的位置,這是不容易確定,當它複製自身如何刪除c#列表中的重複項
3
A
回答
2
我會用Enumerable.Distinct
與邏輯的自定義comparerer:
public class OppositeLocationsEqualComparer : IEqualityComparer<Location>
{
public bool Equals(Location l1, Location l2)
{
if (object.ReferenceEquals(l1, l2)) return true;
if (l1 == null || l2 == null) return false;
return (l1.X == l2.X && l1.Y == l2.Y) || (l1.X == l2.Y && l1.Y == l2.X);
}
public int GetHashCode(Location l)
{
if(l == null) return int.MinValue;
return Math.Abs(l.X - l.Y);
}
}
現在你可以使用Enumerable.Distinct
(和許多其他LINQ方法)與此比較器:
List<Location> uniqueLocations = locationList
.Distinct(new OppositeLocationsEqualComparer())
.ToList();
7
最簡單的解決方案是爲您的點類IEqualityComparer
不關心你X
和的順序,然後您可以使用Distinct
擺脫重複。
public class MyPoint
{
public int X { get; set; }
public int Y { get; set; }
}
public class PointComparer : IEqualityComparer<MyPoint>
{
public bool Equals(MyPoint x, MyPoint y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
return (x.X == y.X && x.Y == y.Y) ||
(x.X == y.Y && x.Y == y.X);
}
public int GetHashCode(MyPoint obj)
{
return (obj?.X.GetHashCode() ?? 0)^(obj?.Y.GetHashCode() ?? 0);
}
}
class Program
{
static void Main()
{
List<MyPoint> data = GetDataFromSomewhere();
var singularData = data.Distinct(new PointComparer()).ToList();
}
}
相關問題
- 1. 從C++列表中刪除重複項
- 2. 刪除陣列中的重複項(C++)
- 3. 如何刪除從列表C#重複
- 4. C#從包含列表的列表中刪除重複項
- 5. 刪除列表中的重複項
- 6. 刪除列表中的重複項
- 7. 從Python列表中刪除重複項
- 8. 從Django列表中刪除重複項
- 9. odoo one2many列表中刪除重複項
- 10. 從Python列表中刪除重複項
- 11. Python從列表中刪除重複項?
- 12. C++,如何橫切鏈接列表,同時刪除重複項
- 13. C#如何過濾列表並刪除重複項?
- 14. 刪除C#中的列表<String[]>中的重複項目
- 15. 刪除Visual Studio 2010中錯誤列表中的重複項(C++)
- 16. 如何從列表中刪除重複
- 17. 刪除列表的重複項,選擇C#中的屬性值?
- 18. 刪除列表中的重複項目在C#
- 19. 添加之前刪除鏈接列表中的重複項 - C
- 20. C:刪除未排序鏈接列表中的重複項
- 21. 如何從列表中刪除連續的重複項?
- 22. 如何刪除列表框中的重複項目
- 23. 如何刪除實例列表中的「重複項」
- 24. 如何刪除列表中的字符串重複項?
- 25. 如何從Clojure的列表中刪除重複項?
- 26. 如何刪除重複項?
- 27. 刪除重複的列表項從列表的列表清單
- 28. C++刪除向量中的重複項
- 29. 使用其他列表的重複項刪除項目列表
- 30. 如何刪除sql中的重複項
你想要刪除除了一個之外的所有東西嗎? –
不,我想刪除相反的位置,因爲我正在改變它們,並且它們會給出相同的結果。因此,如果我有(0,1)和(1,0),我想刪除(1,0)。 @TimSchmelter –
(1,0)和(0,1)是如何重複的? –