As the title says, I'm taking a free online course in C# and I've been stuck on this question for a bit. It's asking to write function with an array that sorts from smallest to largest and removes duplicate entries. The course has gone over arrays and sorting, but not how to remove duplicates so far. If you could help with this I'd appreciate it greatly.
-
2LINQ: `enumerable.OrderBy(x => x).Distinct()` – Mark Shevchenko Jul 02 '17 at 19:47
-
If the course has "gone over sorting" (i.e. you're learning about sorting algorithms), is LINQ based solution appropriate? Which data structures are you allowed to use? – spender Jul 02 '17 at 19:53
-
`public object[] DistinctSortedArray(object[] array) { return array.OrderBy(x => x).Distinct().ToArray(); }` – Alexander Higgins Jul 02 '17 at 20:02
2 Answers
There are a couple of ways to accomplish the task at hand, However, the quickest way is probably using Linq:
int[] array = { 3, 5, 1, -9, 4, 8, 23, -657, 54 };
array = array.Distinct().OrderBy(x => x).ToArray();

- 54,915
- 8
- 91
- 126
While there may be some more efficient methods, to help you understand the concepts a bit more, here's a simple technique.
You'll need to keep track of what entries you've already seen. Create a new list, and add the first number in the array to it. Then, take the second number in the array, and compare it to every number in your list. If it ever shows up in this list, it's a duplicate, so you can skip this number and move to the next element in the array.
ArrayList list = new ArrayList();
for (int i = 0; i < yourUnsortedArray.length; ++i) {
bool hasDuplicate = false;
for (int entry in list ) {
if (yourUnsortedArray[i] == entry) {
hasDuplicate = true;
break;
}
}
if (hasDuplicate == false) {
list.Add(yourUnsortedArray[i]);
}
}
//list will have no duplicates here.
Bonus optimization: It will help if you sort the array first. This way, you only ever have to look at the most recently added number in your list, instead of walking down the entire list every single time.
ArrayList list = new ArrayList();
for (int i = 0; i < yourSortedArray.length; ++i) {
if (list.length == 0 || list[list.length - 1] != yourSortedArray[i]) {
list.Add(yourSortedArray[i]);
}
}

- 2,358
- 1
- 18
- 28
-
This answer is good to explain concepts to newbie. Using ArrayList is a bit too much for newbie. Use just plain simple `int [] unsortedArray` may be a better choice. – Just a HK developer Jul 03 '17 at 02:32