C# List去除重复值

这篇博客探讨了列表去重的三种不同算法实现。第一种是从前往后遍历并删除重复元素;第二种同样从前往后比较,但删除的是后面出现的重复项;第三种方法则是从两头向中间进行比较并移除重复项。每种方法都通过计数器记录了操作次数,展示了不同策略下的效率差异。
摘要由CSDN通过智能技术生成

方法算法一

List<int> trans =new List<int>();         
int count = trans.Count;
 
int time = 0;

count = trans.Count;
for (int i = 0; i < count; i++)
{
    for (int j = i + 1; j < count; j++)
    {
        time++;
        if (trans[i] == trans[j])
        {
            trans.RemoveAt(i);
            count = trans.Count;
            i--;
            break;
        }
}

Debug.LogError($"{trans.Count}/{time}");

           

二从列表第一位开始循环,找到要对比的值和后面值进行对比,如果后面列表有重复删除后面所有重复值

 time = 0;
            count = trans.Count;
            for (int i = 0; i < count; i++)
            {
                for (int j = i + 1; j < count; j++)
                {
                    time++;
                    if (trans[i].GetInstanceID() == trans[j].GetInstanceID())
                    {
                        trans.RemoveAt(j);
                        count = trans.Count;
                        j--;
                    }
                }

            }
            Debug.LogError($"{trans.Count}/{time}");

           

三从两头向中间循环对比查找删除

 time = 0;
count = trans.Count;
for (int i = 0; i < count; i++)
{
    for (int j = count - 1; j > i; j--)
    {
        time++;
        if (trans[i] == trans[j])
        {
            trans.RemoveAt(j);
            count = trans.Count;
        }
    }
}
Debug.LogError($"{trans.Count}/{time}");

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值