How to delete duplicate values in an array? [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove duplicates from array
I have an int array which contains a defined number of elements, all positive. I want to get an array from this one where all the elements appear only once. e.g. If the first array was something like {2000,2011,2011,2012,2009,2009,2000}, I want to get this {2000,2011,2012,2009}. How can I do this? I tried lots of things with for loops but I can't manage to do something good.

With LINQ it's easy:
var intArray = new[] { 2000, 2011, 2011, 2012, 2009, 2009, 2000 };
var uniqueArray = intArray.Distinct().ToArray();
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx
Another way is using Enumerable.GroupBy:
uniqueArray = intArray.GroupBy(i => i).Select(grp => grp.Key).ToArray();

you can do the below
var yourArray = yourArray.Distinct().ToArray();
http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx

Alternative way:
int[] _array = new int[] {1, 2, 1,2}
var myArray = new System.Collections.ArrayList();
foreach(var item in _array){
if (!myArray.Contains(item))
myArray.Add(item);
}

In addition to the other answers, you may want to look at a HashSet, especially if you know ahead of time you will have duplicate values.

Related

How to create LINQ condition with an int Array? [duplicate]

This question already has answers here:
Intersect two arrays
(2 answers)
Closed 5 months ago.
I've got 2 arrays of Int, and I want to keep only elements from second array that contains the first array elements.
int [] first = new int[2] { 1, 2};
int [] second = new int[5] { 99, 1, 2, 97, 95};
I have tried something like below.
foreach(int x in first){
second.Where(s=>s==x);
}
But it doesn't help me because I need to compare both elements from first array
second.Where(s=>s==x[0] && s[1])
and if the int is bigger I need. Do you have any ideas how to get below code line?
second.Where(s=>s==x[0] && s== x[1] && ... && s==x[n])
var elements = second.Where(first.Contains);
Maybe materialize it with a .ToList() or ToArray() call.
If the first list is really large, you could think about a faster version than the .Contains method, but for your lists, it would be overkill.
var firstSet = first.ToHashSet();
var result = second.Where(x => firstSet.Contains(x)).ToArray();

Looking to sort array from smallest to largest remove duplicates [duplicate]

This question already has answers here:
How do I remove duplicates from a C# array?
(28 answers)
Closed 5 years ago.
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.
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();
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]);
}
}

how to get the last three elements from the string array in c# [duplicate]

This question already has answers here:
Using Linq to get the last N elements of a collection?
(20 answers)
how to take all array elements except last element in C#
(6 answers)
Closed 8 years ago.
I have a string array in c#.Now as per my requirement i have to get the last ,second last and one element before second last elements in string but i am not getting how to get it.
Here is my string array.With Last() i am able to get the last element but second last and before second last i am not getting to find out.
string[] arrstr = str.Split(' ');
With .Last() i am able to get the last element but rest of the elements i am not able to get.
Please help me..
Use:
string[] arrstr = str.Reverse().Take(3).Reverse().ToArray();
In more recent versions of c# you can now use:
string[] arrstr = str.TakeLast(3).ToArray();
var threeLastElments = arrstr.Reverse().Take(3).Reverse().ToArray();
It actually gets the number of elements and skip the remaining element from the total count and take the specified amount
you can replace the 3 with N and use as method
string[] res = arrstr.Skip(Math.Max(0, arrstr.Count() - 3)).Take(3).ToArray();
Get a substring:string arrstr = str.Substring(str.Length - 4, 3);
More on C# strings
Why don't you calculate the length using obj.length; and then use arr[i] inside the loop and start the loop from last value.
To offer another solution, one which will be much more performant than LINQ queries ...
public static string[] getLast3(string[] src)
{
if (src.Length <= 3)
return src;
var res = new string[3];
Array.Copy(src, src.Length - 3, res, 0, 3);
return res;
}

Deleting same elements in array C# [duplicate]

This question already has answers here:
How do I remove duplicates from a C# array?
(28 answers)
Closed 9 years ago.
If I have one array for example [1 4 3 7 4 9 5 1 5 6 3].
How to delete repetitive numbers and give in the output array like this [1 4 3 7 9 5 6]?
Distinct()
var distinctArray = myArray.Distinct().ToArray();
You can call your array in a HashSet<int> constructor. HashSet is a kind of optimized collection. It's constructor eliminates the non-unique elements.
Here an example in LINQPad;
var array = new[]{1, 4, 3, 7, 4, 9, 5, 1, 5, 6, 3};
HashSet<int> h = new HashSet<int>(array);
h.ToArray().Dump();
Here a result;
What about this :
int[] arr = { 1, 4, 3, 7, 4, 9, 5, 1, 5, 6, 3 };
foreach (int item in arr.Distinct())
{
Console.WriteLine(item);
}
and you can also assign in a array like this:
int[] unique = arr.Distinct().ToArray();
Couple of suggestions found searching:
1.)
int[] s = { 1, 2, 3, 3, 4};
int[] q = s.Distinct().ToArray();
2.) The easiest solution will be to simply sort the array (takes O(n log n) with standard implementation if you may use them. otherwise consider making an easy randomized quicksort (code is even on wikipedia)).
Afterwards scan it for one additional time. During that scan simple eliminate consecutive identical elements.
If you want to do it in O(n), you can also use a HashSet with elements you have already seen. Just iterate once over your array, for each element check if it is in your HashSet.
If it isn't in there, add it. If it is in there, remove it from the array.
Note, that this will take some additional memory and the hashing will have a constant factor that contributes to your runtime. Althought the time complexity is better, the practical runtime will only be onyl be faster once you exceed a certain array size
If you, for whatever reason, do not want to use Linq:
List<int> distinctList = new List<int>();
foreach (var num in numberList)
{
if (!distinctList.Contains(num))
{
distinctList.Add(num);
}
}

Easier way to populate a list with integers in .NET [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Populating a list of integers in .NET
Is there a simpler or more elegant way of initializing a list of integers in C# other than this?
List<int> numberList = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
or
for(int i = 1; i <= 10; i++)
{
numberList.Add(i);
}
It just doesn't seem very practical - especially if the list was to contain a large number of values. Would a loop be a more practical solution?
Thanks,
CC
You can take advantage of the Enumerable.Range() method:
var numberList = Enumerable.Range(1, 10).ToList();
The first parameter is the integer to start at and the second parameter is how many sequential integers to include.
If your initialization list is as simple as a consecutive sequence of values from from to end, you can just say
var numbers = Enumerable.Range(from, end - from + 1)
.ToList();
If your initialization list is something a little more intricate that can be defined by a mapping f from int to int, you can say
var numbers = Enumerable.Range(from, end - from + 1)
.Select(n => f(n))
.ToList();
For example:
var primes = Enumerable.Range(1, 10)
.Select(n => Prime(n))
.ToList();
would generate the first ten primes assuming that Prime is a Func<int, int> that takes an int n and returns the nth prime.

Categories