Click here to Skip to main content
15,924,318 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hello,
How to remove duplicates in array using function (not using c# in built function) ..
for example there is an array

string[] str={"1","9","2","7","2","1","9","9"}

i want to remove duplicates from this and form new aaray like

string[] newstr={"1","9","2","7"}


Thanks & Regards
Srishti Gupta
Posted
Updated 27-May-20 7:22am

C#
string[] str={"1","9","2","7","2","1","9","9"};
string[] newstr = new HashSet<string>(str).ToArray();</string>

Happy Coding!
:)
 
Share this answer
 
Comments
srishti056 8-Jul-13 4:52am    
i wanna a function for this not in built function of c#
Quote:
not using c# in built function

Why not? You can simply use the Distinct method instead of writing a method yourself:
C#
string[] newstr = str.Distinct().ToArray();

It's really not necessary to write a method yourself.

[Edit]

If you really want a function that's not built-in, create this extension method:
C#
public static class ExtensionMethods
{
    public static IEnumerable<T> DistinctNonBuiltIn<T>(this IEnumerable<T> source)
    {
        List<T> distinctValues = new List<T>();
        foreach (T val in source)
        {
            if (!distinctValues.Contains(val))
            {
                distinctValues.Add(val);
            }
        }
        return (IEnumerable<T>)distinctValues;
    }
}

And to get the distinct values:
C#
string[] newstr = str.DistinctNonBuiltIn().ToArray();

Hope this helps.
 
Share this answer
 
v3
Comments
srishti056 8-Jul-13 4:52am    
ya actually its a interview question and he said that write a function itself
Thomas Daniels 8-Jul-13 5:19am    
I updated my answer.
From StackOverFlow.

C#
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));
   }
 
Share this answer
 
Comments
srishti056 8-Jul-13 5:15am    
ok thanks
Sushil Mate 8-Jul-13 5:23am    
by the way you should try it by your self first. don't put the question here unless you are stuck somewhere. see next time interviewer will ask another question, it doesn't necessarily they will ask the same question. better to try by yourself. Learn to code not to mug up.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900