'How to sort and remove duplicates from string Array without using the inbuilt function?
I want to remove duplicate string also sort the string array in C#
I am reading text file which contains data like Blue, Green, Red, Green, Yellow so I am reading data using File.ReadAllLines()
which return an array of string now how to sort and remove duplicate.
private string[] sortArray(string[] str)
{
int cnt = str.Length - 1;
for (int i = 0; i < cnt; i++)
{
for (int j = cnt; j > i; j--)
{
if (((IComparable)str[j - 1]).CompareTo(str[j]) > 0)
{
var temp = str[j - 1];
str[j - 1] = str[j];
str[j] = temp;
}
}
}
return str;
}
using this above code I can sort the array but how to remove the duplicate string thanks in advance :)
Solution 1:[1]
Here is what you can do
List<string> colorList = new List<string> { "Yellow", "Blue", "Green", "Red", "Blue", "Green", "Red", "Green", "Green", "Yellow" };
colorList = colorList.Distinct().OrderBy(item=> item).ToList();
File.ReadAllLines()
will give you string[]
and you can apply Dictinct and OrderBy in the same way as mentioned above
Sorting & remove duplicate without using build-in functions
Create a call to methods like this
string[] colorArray = new string[] { "Yellow", "Blue", "Green", "Red", "Blue", "Green", "Red", "Green", "Green", "Yellow" };
colorArray = RemoveDuplicates(colorArray);
Sort(colorArray);
sort using below method
static void Sort(string[] sa)
{
int pos = 1;
while (pos < sa.Length)
{
if (String.Compare(sa[pos], sa[pos - 1], StringComparison.OrdinalIgnoreCase) >= 0)
{
pos++;
}
else
{
string temp = sa[pos];
sa[pos] = sa[pos - 1];
sa[pos - 1] = temp;
if (pos > 1) pos--;
}
}
}
Remove duplicates using this one
static string[] RemoveDuplicates(string[] inputArray)
{
int length = inputArray.Length;
for (int i = 0; i < length; i++)
{
for (int j = (i + 1); j < length;)
{
if (inputArray[i] == inputArray[j])
{
for (int k = j; k < length - 1; k++)
inputArray[k] = inputArray[k + 1];
length--;
}
else
j++;
}
}
string[] distinctArray = new string[length];
for (int i = 0; i < length; i++)
distinctArray[i] = inputArray[i];
return distinctArray;
}
Solution 2:[2]
We can remove duplicate items using below code. In below code instead stack you can use any collection like List, Dictionary and etc. That supports contains function. Using any existing sorting algorithm you can sort the items
string[] colorArray = new string[] { "Yellow", "Blue", "Green", "Red", "Blue", "Green", "Red", "Green", "Green", "Yellow" };
Stack<string> strStacks = new Stack<string>();
for (int i = 0; i < colorArray.Length; i++)
{
if (strStacks.Contains(colorArray[i]))
{
continue;
}
else
{
strStacks.Push(colorArray[i]);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |