سؤال

لقد كنت أعمل مع أ string[] المصفوفة في C# التي يتم إرجاعها من استدعاء دالة.من الممكن أن ألقي إلى أ Generic المجموعة، لكنني كنت أتساءل عما إذا كانت هناك طريقة أفضل للقيام بذلك، ربما باستخدام مصفوفة مؤقتة.

ما هي أفضل طريقة لإزالة التكرارات من مجموعة C#؟

هل كانت مفيدة؟

المحلول

ربما يمكنك استخدام استعلام LINQ للقيام بذلك:

int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();

نصائح أخرى

هنا هو مجموعة التجزئة<سلسلة> يقترب:

public static string[] RemoveDuplicates(string[] s)
{
    HashSet<string> set = new HashSet<string>(s);
    string[] result = new string[set.Count];
    set.CopyTo(result);
    return result;
}

لسوء الحظ، يتطلب هذا الحل أيضًا .NET Framework 3.5 أو إصدار أحدث حيث لم تتم إضافة HashSet حتى هذا الإصدار.يمكنك أيضًا استخدام مصفوفة مميزة (), ، وهي إحدى ميزات LINQ.

إذا كنت بحاجة إلى فرزها، فيمكنك تنفيذ فرز يزيل التكرارات أيضًا.

ثم يضرب عصفورين بحجر واحد.

سوف يقوم الكود الذي تم اختباره والعمل به بإزالة التكرارات من المصفوفة.يجب عليك تضمين مساحة الاسم System.Collections.

string[] sArray = {"a", "b", "b", "c", "c", "d", "e", "f", "f"};
var sList = new ArrayList();

for (int i = 0; i < sArray.Length; i++) {
    if (sList.Contains(sArray[i]) == false) {
        sList.Add(sArray[i]);
    }
}

var sNew = sList.ToArray();

for (int i = 0; i < sNew.Length; i++) {
    Console.Write(sNew[i]);
}

يمكنك تحويل هذا إلى وظيفة إذا أردت ذلك.

قد يعتمد هذا على مدى رغبتك في هندسة الحل - إذا لم تكن المصفوفة بهذا الحجم أبدًا ولا تهتم بفرز القائمة، فقد ترغب في تجربة شيء مشابه لما يلي:

    public string[] RemoveDuplicates(string[] myList) {
        System.Collections.ArrayList newList = new System.Collections.ArrayList();

        foreach (string str in myList)
            if (!newList.Contains(str))
                newList.Add(str);
        return (string[])newList.ToArray(typeof(string));
    }

-- هذا هو سؤال المقابلة سأل في كل مرة.الآن انتهيت من الترميز.

static void Main(string[] args)
{    
            int[] array = new int[] { 4, 8, 4, 1, 1, 4, 8 };            
            int numDups = 0, prevIndex = 0;

            for (int i = 0; i < array.Length; i++)
            {
                bool foundDup = false;
                for (int j = 0; j < i; j++)
                {
                    if (array[i] == array[j])
                    {
                        foundDup = true;
                        numDups++; // Increment means Count for Duplicate found in array.
                        break;
                    }                    
                }

                if (foundDup == false)
                {
                    array[prevIndex] = array[i];
                    prevIndex++;
                }
            }

            // Just Duplicate records replce by zero.
            for (int k = 1; k <= numDups; k++)
            {               
                array[array.Length - k] = '\0';             
            }


            Console.WriteLine("Console program for Remove duplicates from array.");
            Console.Read();
        }
List<String> myStringList = new List<string>();
foreach (string s in myStringArray)
{
    if (!myStringList.Contains(s))
    {
        myStringList.Add(s);
    }
}

هذا هو يا (ن ^ 2), ، وهو أمر لن يكون مهمًا بالنسبة للقائمة القصيرة التي سيتم حشوها في مجموعة كبيرة، ولكنها قد تشكل مشكلة بسرعة في مجموعة كبيرة.

protected void Page_Load(object sender, EventArgs e)
{
    string a = "a;b;c;d;e;v";
    string[] b = a.Split(';');
    string[] c = b.Distinct().ToArray();

    if (b.Length != c.Length)
    {
        for (int i = 0; i < b.Length; i++)
        {
            try
            {
                if (b[i].ToString() != c[i].ToString())
                {
                    Response.Write("Found duplicate " + b[i].ToString());
                    return;
                }
            }
            catch (Exception ex)
            {
                Response.Write("Found duplicate " + b[i].ToString());
                return;
            }
        }              
    }
    else
    {
        Response.Write("No duplicate ");
    }
}

هنا أ يا (ن * ن) النهج الذي يستخدم يا(1) فضاء.

void removeDuplicates(char* strIn)
{
    int numDups = 0, prevIndex = 0;
    if(NULL != strIn && *strIn != '\0')
    {
        int len = strlen(strIn);
        for(int i = 0; i < len; i++)
        {
            bool foundDup = false;
            for(int j = 0; j < i; j++)
            {
                if(strIn[j] == strIn[i])
                {
                    foundDup = true;
                    numDups++;
                    break;
                }
            }

            if(foundDup == false)
            {
                strIn[prevIndex] = strIn[i];
                prevIndex++;
            }
        }

        strIn[len-numDups] = '\0';
    }
}

ال التجزئة/لينق الأساليب المذكورة أعلاه هي ما ستستخدمه بشكل عام في الحياة الواقعية.ولكن في المقابلات عادة ما يريدون وضع بعض القيود، على سبيل المثال:مساحة ثابتة تستبعد التجزئة أو لا توجد داخلية واجهة برمجة التطبيقات - الذي يستبعد استخدامه لينك.

أضف كافة السلاسل إلى القاموس واحصل على خاصية المفاتيح بعد ذلك.سيؤدي هذا إلى إنتاج كل سلسلة فريدة من نوعها، ولكن ليس بالضرورة بنفس الترتيب الذي وردت فيه المدخلات الأصلية.

إذا كنت تطلب أن تكون النتيجة النهائية بنفس ترتيب الإدخال الأصلي، فعند النظر في التواجد الأول لكل سلسلة، استخدم الخوارزمية التالية بدلاً من ذلك:

  1. احصل على قائمة (الناتج النهائي) وقاموس (للتحقق من التكرارات)
  2. بالنسبة لكل سلسلة في الإدخال، تحقق مما إذا كانت موجودة في القاموس بالفعل
  3. إذا لم يكن الأمر كذلك، قم بإضافته إلى القاموس وإلى القائمة

وفي النهاية، تحتوي القائمة على أول ظهور لكل سلسلة فريدة.

تأكد من مراعاة أشياء مثل الثقافة وما شابه ذلك عند إنشاء قاموسك، للتأكد من أنك تتعامل مع التكرارات ذات الحروف المميزة بشكل صحيح.

يحاول الجزء التالي من التعليمات البرمجية إزالة التكرارات من ArrayList على الرغم من أن هذا ليس الحل الأمثل.لقد سُئل هذا السؤال خلال إحدى المقابلات لإزالة التكرارات من خلال التكرار، ودون استخدام قائمة مصفوفات ثانية/مؤقتة:

private void RemoveDuplicate() 
{

ArrayList dataArray = new ArrayList(5);

            dataArray.Add("1");
            dataArray.Add("1");
            dataArray.Add("6");
            dataArray.Add("6");
            dataArray.Add("6");
            dataArray.Add("3");
            dataArray.Add("6");
            dataArray.Add("4");
            dataArray.Add("5");
            dataArray.Add("4");
            dataArray.Add("1");

            dataArray.Sort();

            GetDistinctArrayList(dataArray, 0);
}

private void GetDistinctArrayList(ArrayList arr, int idx)

{

            int count = 0;

            if (idx >= arr.Count) return;

            string val = arr[idx].ToString();
            foreach (String s in arr)
            {
                if (s.Equals(arr[idx]))
                {
                    count++;
                }
            }

            if (count > 1)
            {
                arr.Remove(val);
                GetDistinctArrayList(arr, idx);
            }
            else
            {
                idx += 1;
                GetDistinctArrayList(arr, idx);
            }
        }

ربما Hashset التي لا تخزن عناصر مكررة وتجاهل بصمت طلبات إضافة التكرارات.

static void Main()
{
    string textWithDuplicates = "aaabbcccggg";     

    Console.WriteLine(textWithDuplicates.Count());  
    var letters = new HashSet<char>(textWithDuplicates);
    Console.WriteLine(letters.Count());

    foreach (char c in letters) Console.Write(c);
    Console.WriteLine("");

    int[] array = new int[] { 12, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 };

    Console.WriteLine(array.Count());
    var distinctArray = new HashSet<int>(array);
    Console.WriteLine(distinctArray.Count());

    foreach (int i in distinctArray) Console.Write(i + ",");
}

ملحوظة :لم تختبر!

string[] test(string[] myStringArray)
{
    List<String> myStringList = new List<string>();
    foreach (string s in myStringArray)
    {
        if (!myStringList.Contains(s))
        {
            myStringList.Add(s);
        }
    }
    return myStringList.ToString();
}

ربما تفعل ما تحتاجه ...

يحرر ارغ !!!تعرض للضرب عليه بالسرقة بأقل من دقيقة!

اختبار أدناه ويعمل.الأمر الرائع هو أنه يقوم بإجراء بحث حساس للثقافة أيضًا

class RemoveDuplicatesInString
{
    public static String RemoveDups(String origString)
    {
        String outString = null;
        int readIndex = 0;
        CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;


        if(String.IsNullOrEmpty(origString))
        {
            return outString;
        }

        foreach (var ch in origString)
        {
            if (readIndex == 0)
            {
                outString = String.Concat(ch);
                readIndex++;
                continue;
            }

            if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1)
            {
                //Unique char as this char wasn't found earlier.
                outString = String.Concat(outString, ch);                   
            }

            readIndex++;

        }


        return outString;
    }


    static void Main(string[] args)
    {
        String inputString = "aAbcefc";
        String outputString;

        outputString = RemoveDups(inputString);

        Console.WriteLine(outputString);
    }

}

--أبتسينسديت

يقوم هذا الرمز بإزالة القيم المكررة بنسبة 100% من المصفوفة [كما استخدمت a[i]] ..... يمكنك تحويله بأي لغة OO .....:)

for(int i=0;i<size;i++)
{
    for(int j=i+1;j<size;j++)
    {
        if(a[i] == a[j])
        {
            for(int k=j;k<size;k++)
            {
                 a[k]=a[k+1];
            }
            j--;
            size--;
        }
    }

}

حل بسيط:

using System.Linq;
...

public static int[] Distinct(int[] handles)
{
    return handles.ToList().Distinct().ToArray();
}

طريقة التمديد العامة :

public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
    if (source == null)
        throw new ArgumentNullException(nameof(source));

    HashSet<TSource> set = new HashSet<TSource>(comparer);
    foreach (TSource item in source)
    {
        if (set.Add(item))
        {
            yield return item;
        }
    }
}

يمكنك استخدام هذا الرمز عند العمل مع ArrayList

ArrayList arrayList;
//Add some Members :)
arrayList.Add("ali");
arrayList.Add("hadi");
arrayList.Add("ali");

//Remove duplicates from array
  for (int i = 0; i < arrayList.Count; i++)
    {
       for (int j = i + 1; j < arrayList.Count ; j++)
           if (arrayList[i].ToString() == arrayList[j].ToString())
                 arrayList.Remove(arrayList[j]);
public static int RemoveDuplicates(ref int[] array)
{
    int size = array.Length;

    // if 0 or 1, return 0 or 1:
    if (size  < 2) {
        return size;
    }

    int current = 0;
    for (int candidate = 1; candidate < size; ++candidate) {
        if (array[current] != array[candidate]) {
            array[++current] = array[candidate];
        }
    }

    // index to count conversion:
    return ++current;
}

يوجد أدناه منطق بسيط في Java، حيث يمكنك اجتياز عناصر المصفوفة مرتين، وإذا رأيت أي عنصر نفسه، فقم بتعيين صفر له بالإضافة إلى أنك لا تلمس فهرس العنصر الذي تقارنه.

import java.util.*;
class removeDuplicate{
int [] y ;

public removeDuplicate(int[] array){
    y=array;

    for(int b=0;b<y.length;b++){
        int temp = y[b];
        for(int v=0;v<y.length;v++){
            if( b!=v && temp==y[v]){
                y[v]=0;
            }
        }
    }
}
  private static string[] distinct(string[] inputArray)
        {
            bool alreadyExists;
            string[] outputArray = new string[] {};

            for (int i = 0; i < inputArray.Length; i++)
            {
                alreadyExists = false;
                for (int j = 0; j < outputArray.Length; j++)
                {
                    if (inputArray[i] == outputArray[j])
                        alreadyExists = true;
                }
                        if (alreadyExists==false)
                        {
                            Array.Resize<string>(ref outputArray, outputArray.Length + 1);
                            outputArray[outputArray.Length-1] = inputArray[i];
                        }
            }
            return outputArray;
        }
using System;
using System.Collections.Generic;
using System.Linq;


namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
             List<int> listofint1 = new List<int> { 4, 8, 4, 1, 1, 4, 8 };
           List<int> updatedlist= removeduplicate(listofint1);
            foreach(int num in updatedlist)
               Console.WriteLine(num);
        }


        public static List<int> removeduplicate(List<int> listofint)
         {
             List<int> listofintwithoutduplicate= new List<int>();


              foreach(var num in listofint)
                 {
                  if(!listofintwithoutduplicate.Any(p=>p==num))
                        {
                          listofintwithoutduplicate.Add(num);
                        }
                  }
             return listofintwithoutduplicate;
         }
    }



}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top