HI WELCOME TO SIRIS

C# program to remove duplicates

Leave a Comment
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());
        }
    }
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.