Friday, 3 May 2019

Write a single method which can be passed either any type of arrays and it returns the list of unique items in the specified list




1.    Consider the following two arrays:

string[] arrStrings = new string[] { “Bal”, “Yuriy”, “Ken”, “Apple”, “Ken” };
int[] arrNumbers = new int[] { 11, 2, 25, 34, 66, 25, 0, 0, 3, 4, 2, 89 };


Write a single method which can be passed either one of these arrays and it returns the list of unique items in the specified list. You cannot use LINQ to solve this problem.using System;


using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arrStrings = new string[] { "Bal", "Yuriy", "Ken", "Apple", "Ken" };
            int[] arrNumbers = new int[] { 11, 2, 25, 34, 66, 25, 0, 0, 3, 4, 2, 89 };
            
            //For Integer arrays
            List<int> objIntList = new List<int>();
            objIntList = GetUniqueList<int>(arrNumbers);

            //For String arrays
            List<string> objStringList = new List<string>();
            objStringList = GetUniqueList<string>(arrStrings);
        }

    

        private static List<T> GetUniqueList<T>(T[] arraMix)
        {
            List<T> objUniqueList = new List<T>();
            foreach (var chkTest in arraMix)
            {
                if (!objUniqueList.Contains(chkTest))
                {
                    objUniqueList.Add(chkTest);
                }
            }
            return objUniqueList;
        }
    }
}















No comments:

Post a Comment