Hi all,
This is the code below which gives me the error mentioned in subject:
Here i want to extract the unique elements: output should be {1,3,5,9}
public static void Main()
{
int[] number={1,1,3,3,3,5,5,5,9,9,9,9};
int n = number.Length;
for (int i = 0; i < n; i++)
{
if (number[i] != number[i + 1])
{
Console.WriteLine(number[i]);
}
}
}
Thanks in advance
Loading
VulpesPosted Jun 26, 2012, 6:23 AM
Santhosh Kumar JayaramanPosted Jun 26, 2012, 6:40 AM
rani m mkPosted Jun 26, 2012, 6:36 AM
public static void Main()
{ int[] number={9,9,3, 1,1,5,5,5,3,3,9,9};
int n = number.Length;
Array.Sort(number);
Console.WriteLine(number[0]);
for (int i = 1; i < n; i++)
{
if (number[i] != number[i - 1])
{
Console.WriteLine(number[i]);
}
}
}
Jignesh TrivediPosted Jun 26, 2012, 6:32 AM
Santosh and Vulpes both are right
you can also use linq to object for sorting and get distinct value
int[] number = { 9, 9, 3, 1, 1, 5, 5, 5, 3, 3, 9, 9 };
int[] mynumber = number.Distinct().OrderBy(num => num).ToArray();
foreach (int i in mynumber)
{
Console.WriteLine(i);
}
hope this will help you.
VulpesPosted Jun 26, 2012, 6:31 AM
Did you change the for statement so that 'i' starts from 1 rather than 0?
rani m mkPosted Jun 26, 2012, 6:29 AM
rani m mkPosted Jun 26, 2012, 6:25 AM
It is sorted list only
Santhosh Kumar JayaramanPosted Jun 26, 2012, 6:20 AM
VulpesPosted Jun 26, 2012, 6:14 AM
Santhosh Kumar JayaramanPosted Jun 26, 2012, 6:11 AM
.Distinct() extension method will helps you to get unique element.
public static void Main()
{
int[] number = { 1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9 };
foreach (int i in number.Distinct())
{
Console.WriteLine(i);
}
Console.Read();
}