How to find distinct values from array C# Linq

Posted by Laghaterohan under C# on 7/17/2013 | Points: 10 | Views : 10285 | Status : [Member] | Replies : 2
Hi,
one of my method returns me an array which has several fields say, id1, id2 ,id3 etc...
how I want to make list of distinct ids from this id1,id2,id3. Can any one help me out how to do this using C#, LINQ ??

Please help.

Best Regards,
Rohan Laghate



Responses

Posted by: Prabhat39 on: 7/17/2013 [Member] Starter | Points: 25

Up
0
Down
You can use distinct() method of linq. Below is the sample code.
int[] num = {1,3,4,2,4,2,4,5,2};
var disNum = num.Distinct();
foreach (int i in disNum)
{
Console.WriteLine(i);
}

Regards,
Prabhat Kumar

Laghaterohan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Satyapriyanayak on: 7/17/2013 [Member] [MVP] Silver | Points: 25

Up
0
Down
Method-1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Remove_duplicate
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Original Names");

string[] strs = new string[4] { "Raj", "Ravi", "Ravi", "Rahul" };

for (int i = 0; i < strs.Length; i++)
{

Console.WriteLine(strs[i]);

}

Console.WriteLine("Distinct Names");

var Results = strs.Distinct();

foreach (var item in Results)
{

Console.WriteLine(item);

}

Console.ReadLine();


}
}
}

Method-2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Remove_duplicate
{
class Program
{
static void Main(string[] args)
{


String[] myString = new String[] { "Raj", "Raj", "Ravi", "Ravi", "Rahul" };

IEnumerable<String> disctinctName = myString.Distinct();

foreach (String theString in disctinctName)
{

Console.WriteLine(theString);

}

Console.ReadLine();
}
}
}




If this post helps you mark it as answer
Thanks

Laghaterohan, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response