简体   繁体   English

c# 从数组中删除所有相同的对象(无 LINQ)

[英]c# remove alle the same objects from array (without LINQ)

I can't remove all the same object from an array in c#.我无法从 c# 的数组中删除所有相同的 object。 The last doesn't removed.最后一个没有删除。

I add the objects in an array I add them more then one time.我将对象添加到一个数组中,我添加它们不止一次。

When I try to remove them not all objects are removed.当我尝试删除它们时,并非所有对象都被删除。

How can I remove all the same objects.如何删除所有相同的对象。

static void Main(string[] args)
{
    Cirkel c1 = new Cirkel(2);
    Cirkel c2 = new Cirkel(3);

    Figuur f1 = new Figuur();
    f1.Add(c1);
    f1.Add(c1);
    f1.Add(c2);
    f1.Add(c2);

    f1.VerwijderObject(c2);
}

class Figuur
{
    public Figuur[] _Items = new Figuur[0];
    int count = 0;

    public void Add(Figuur figuur)
    {
        count = count + 1;
        Array.Resize(ref _Items, count);
        _Items[count - 1] = figuur;
    }

    public void VerwijderObject(Figuur figuur)
    {
        for (int k = 0; k < _Items.Length; k++)
        {
            if (_Items[k].Equals(figuur))
            {
                for (int i = k; i < (count - 1); i++)
                {
                    _Items[i] = _Items[i + 1];
                }
                count = count - 1;
                Array.Resize(ref _Items, count);
            }
        }
    }
}

By default, Equals does a reference equals comparison.默认情况下,Equals 进行引用等于比较。 You need to override Equals method in in Cirkel class (you have not provided the code for Cirkel, so don't know what it does).您需要在 Cirkel class 中覆盖 Equals 方法(您没有提供 Cirkel 的代码,所以不知道它的作用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM