簡體   English   中英

從列表中刪除重復項<double[]>

[英]Removing duplicates from List<double[]>

我正在嘗試從雙精度數組列表中刪除重復項。 我想保留重復的第一個實例,但刪除之后找到的所有實例。

這是我的代碼:

private static List<double[]> RemoveDupes(List<double[]> locData)
    {
        List<double[]> list = locData;
        while (ContainsDupes(list))
            for (int a = 0; a < list.Count; a++)
                for (int b = 0; b < list.Count; b++)
                    if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                        list.RemoveAt(b);

        return list;
    }
private static bool ContainsDupes(List<double[]> list)
    {
        for (int a = 0; a < list.Count; a++)
            for (int b = 0; b < list.Count; b++)
                if (a != b && list[a][0] == list[b][0] && list[a][1] == list[b][1])
                    return true;
        return false;
    }

該方法幾乎在所有時間都有效,但是它很慢,並且在極少數情況下(幾千分之一)使我的程序崩潰,並在第6行出現了索引異常。我想不出任何其他方式來做到這一點,所以對您沒有幫助將不勝感激。

輸入:

{{45.5, 23.6}, {34.54, 98.34}, {45.5, 23.6}}

所需的輸出:

{{45.5, 23.6}, {34.54, 98.34}}

(double []的長度始終為2)

既然您已經說過數組的大小將始終為2,所以建議您使用其他數據類型。 例如, 元組會更合適,因為它們實際上是一對值。

例如,您可以定義對的集合:

List<(double, double)> pairs = new List<(double, double)>(); //C# 7.1+

List<Tuple<double, double>> pairsCollection = new List<Tuple<double, double>>(); // C# 7 or less

以這種方式播種:

pairs.Add((45.5, 23.6));
pairs.Add((34.54, 98.34));
pairs.Add((45.5, 23.6));

而且,僅使用Distinct方法即可刪除重復項:

pairs.Distinct();

這將輸出:

{{45.5,23.6},{34.54,98.34}}

另外,如果您不能更改數據類型,則可以將集合投影為成對的集合,然后將其區分:

List<double[]> collection = new List<double[]>()
{
    new double[]{45.5, 23.6},
    new double[]{34.54, 98.34},
    new double[]{45.5, 23.6}
};
var pairs = collection.Select(pa => (pa[0], pa[1])); 
var distinctPairs = pairs.Distinct();

您可以使用https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable.sequenceequal?redirectedfrom=MSDN&view=netframework-4.8#System_Linq_Enumerable_SequenceEqual__1_System_Collections_Generic_IEnumerable___0__System_Collections_Generic_IEnumerable__

var l = new List<int[]>(){
            new int[]{5,4,3},
            new int[]{5,4,3},
            new int[]{5,4,2},
            };

            var indexStore = new List<int>();

            for (int i = 0; i < l.Count - 1; i++)
            {
                for (int x = i + 1; x < l.Count-1; x++)
                {
                    if (l[i].SequenceEqual(l[x]))
                    {
                        indexStore.Add(x);
                    }
                }
            }

            foreach (var index in indexStore)
            {
                l.RemoveAt(index);
            }

循環時不要刪除,以更好地存儲重復索引

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM