简体   繁体   中英

Converting usage of VB6 err object to C#

Below is my vb6 code how can i convert this into c#, Actually i'm getting confusion in that handling of err in if condition.

Function FilterDuplicates(Arr As Variant) As Long
Dim col As Collection, Index As Long, dups As Long
Set col = New Collection
On Error Resume Next
For Index = LBound(Arr) To UBound(Arr)
    col.Add 0, CStr(Arr(Index))
    If err Then
        Arr(Index) = Empty
        dups = dups + 1
        err.Clear
    ElseIf dups Then
        Arr(Index - dups) = Arr(Index)
        Arr(Index) = Empty
    End If
Next
FilterDuplicates = dups      End Function

Below is my C# Code which i tried and here actually i'm unable to handle this If condition part.

        private long FilterDuplicates(string[] Arr)
    {
        Collection col = new Collection();
        long Index=0;
        long dups =0;    
        try
        {
            for (Index = Arr.GetLowerBound(0); Index <= Arr.GetUpperBound(0); Index++)
            {
                col.Add(0, Conversion.Str(Arr[Index]));
                if (Information.Err)
                {
                    Arr[Index] = null;
                    dups += 1;
                    err.Clear;
                }
                else if (dups != 0)
                {
                    Arr[Index - dups] = Arr[Index];
                    Arr[Index] = null;
                }
            }
            return dups;
        }
        catch
        {

        }
    }

Often it's easier to implement the routine than convert it. It seems, you want

  1. Change each duplcate (ie second, third etc value) into null
  2. Count all such changes

If it's your case, you can try

 private static long FilterDuplicates(string[] Arr) {
   HashSet<string> appeared = new HashSet<string>();

   long result = 0;  

   for (int i = 0; i < Arr.Length; ++i)       
     if (!appeared.Add(Arr[i])) {
       result += 1;

       Arr[i] = null;
     }

   return result;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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