Hi I'm working on this simple program that takes 5 numbers from user as long as the numbers are greater than 10 and less than 100. My goal is to remove duplicates numbers an ONLY show the NOT DUPLICATE numbers. Let's say if I enter 23 , 23, 40, 56 , 37 I should only output 40 , 56 , 37. Please help me on this. Thanks in advance. Here's my code:
static void Main(string[] args)
{
int[] arr = new int[5];
for (int i = 0; i < 5; i++)
{
Console.Write("\nPlease enter a number between 10 and 100: ");
int number = Convert.ToInt32(Console.ReadLine());
if (number > 10 && number <= 100)
{
arr[i] = number;
}
else {
i--;
}
}
int[] arr2 = arr.Distinct().ToArray();
Console.WriteLine("\n");
for (int i = 0; i < arr2.Length; i++)
{
Console.WriteLine("you entered {0}", arr2[i]);
}
Console.ReadLine();
}
-
possible duplicate of thisDebosmit Ray– Debosmit Ray2016年03月02日 04:10:41 +00:00Commented Mar 2, 2016 at 4:10
-
@Ian I think he dont want to show the duplicate values in the list.. Distinct will include it onceOlivarsham– Olivarsham2016年03月02日 04:12:37 +00:00Commented Mar 2, 2016 at 4:12
-
@Olivarsham YES I dont want to show duplicate values. As you can see I'm already using Distinct() , but I dont want to show duplicate values. Any ideas how to fix that?user5880939– user58809392016年03月02日 04:14:20 +00:00Commented Mar 2, 2016 at 4:14
-
You can surely bend LINQ to solve this problem. But given that this is clearly a beginning programmer's exercise, you would be much better served by writing the algorithm yourself. As stated, the question is too broad; even limiting solutions to LINQ, there are many possible solutions. Please show an attempt to solve the problem, explaining precisely what you are having trouble withPeter Duniho– Peter Duniho2016年03月02日 04:17:18 +00:00Commented Mar 2, 2016 at 4:17
-
OK, I updated my answer.Ian– Ian2016年03月02日 04:19:10 +00:00Commented Mar 2, 2016 at 4:19
3 Answers 3
One way is to group the elements based on input number and filter groups whose count is 1
int[] arr2 = arr.GroupBy(e=>e)
.Where(e=>e.Count() ==1)
.Select(e=>e.Key).ToArray();
Comments
I think you are looking for this:
int[] arr2 = arr.GroupBy(x => x)
.Where(dup=>dup.Count()==1)
.Select(res=>res.Key)
.ToArray();
Input Array : 23 , 23, 40, 56 , 37
Output Array : 40 , 56 , 37
How it Works:
arr.GroupBy(x => x)
=> give a collection of{System.Linq.GroupedEnumerable<int,int,int>}
where x.Key gives you the unique elements..Where(dup=>dup.Count()==1)
=> Extracts the theKeyValuePairs
that contains Values count exactly equal to1
.Select(res=>res.Key)
=> will collects the Keys from the above result
Comments
In your case, perhaps a combination of LINQ methods would be needed:
int[] arr2;
int[] nodupe = arr2.GroupBy(x => x).Where(y => y.Count() < 2).Select(z => z.Key).ToArray();