MVC ASP.NET C# SQL Server WCF Written Test HR Round Subscribe C# Videos C# Programs Buy DVD

C# program to remove duplicates


Write a c# program to print unique names, by removing the duplicate entries. For example, in the Input String below, Rob and Able names are repeated twice. The c# program that you write should remove the duplicates and return the string as shown in Output String. The output string contains each name only once, eliminating duplicates.


Input String    = "Rob;Mike;Able;Sara;Rob;Peter;Able;"
Output String = "Rob;Mike;Able;Sara;Peter;"

using System;
using System.Linq;
using System.Text;


namespace SamplePrograms
{
    class PrintUniqueNames
    {
        public static void Main()
        {
            // Prompt the user to enter the list of user names
            Console.WriteLine("Please enter list of names seperated by semi colon");


            // Read the user name list from the console
            string strUserNames = Console.ReadLine();


            // Sampe list of user names that can be used as an input
            // strUserNames = "Rob;Mike;Able;Sara;Rob;Peter;Able";


            // Split the string into a string array based on semi colon
            string[] arrUsersNames = strUserNames.Split(';');


            // Use the Distinct() LINQ function to remove duplicates
            string[] arrUniqueNames = arrUsersNames.Distinct().ToArray();


            // Using StringBuilder to concatenate strings is more efficient
            // than using immutable string objects for better performance
            StringBuilder sbUniqueUsernames = new StringBuilder();


            // Build the string from unique names appending semi colon
            foreach (string strName in arrUniqueNames)
            {
                sbUniqueUsernames.Append(strName + ";");
            }


            // Remove the extra semi colon in the end
            sbUniqueUsernames.Remove(sbUniqueUsernames.ToString().LastIndexOf(';'), 1);


            // Finally print the unique names
            Console.WriteLine();
            Console.WriteLine("Printing names without duplicates");
            Console.WriteLine(sbUniqueUsernames.ToString());
        }
    }
}

2 comments:

  1. The C# String class has a built in Join method, which takes a separator string and an array of strings to join.
    So we can easily get the final string without appending individual substrings to a StringBuilder instance:

    string strUniqueNames = String.Join(";", strUserNames.Split(';').Distinct().ToArray());

    ReplyDelete
    Replies
    1. I ignore your point ..
      string strUniqueNames = String.Join(";", strUserNames.Split(';').Distinct().ToArray());

      Delete