Click here to Skip to main content
16,018,818 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi
I would like get data from list, which is used more time.
e.g. I have a list who contains items 1,2,5,2,8,7,8,2
I want only item who is more time 2,2,8,8,2

Is for this some method or?

I create my way this...
foreach and List.Contains and last step add to new List.

Thank you
Posted

Hello ,
Even Try The Following
C#
List<int> list = new List<int>() { 1, 3, 3, 4, 5, 6, 6, 7, 8 };
var x = list.GroupBy(x=>x).FirstOrDefault(g=>g.Count()>1).Key;//C#3
 
Share this answer
 
v2
Hi
Thank you for quickly solution
 
Share this answer
 
Comments
Afzaal Ahmad Zeeshan 27-Nov-14 5:28am    
You should always post things like this as comments to the post and not as answers. :-)
Since you tagged as LINQ, here is a LINQ method solution:

C#
            List<int> data = "1,2,5,2,8,7,8,2".Split(',').Select(s => int.Parse(s)).ToList();  //Setup input list

            List<int> repeats = data.GroupBy(i => i).Where(g => g.Count() != 1).Select(g => g.Key).ToList(); // So it's done once only.
            List<int> duplicates = data.Where(i => repeats.Contains(i)).ToList();

            foreach (int i in duplicates) Console.WriteLine(i);
</int>
 
Share this answer
 
Hello,

C#
var input = new List<int>() { 1, 2, 5, 2, 8, 7, 8, 2 };
var output = (from x in input
                where input.Count(c => c == x) > 1
                select x).ToList();

Console.WriteLine(string.Join(", ", input));
Console.WriteLine(string.Join(", ", output));


I hope it help you.
 
Share this answer
 
v3
Try this code, it would work for you to get the only elements that are duplicated in the List.

C#
// example list that I tried in my IDE, write your own list here
List<int> list = new List<int>() { 1, 3, 3, 4, 5, 6, 6, 7, 8 };
// run the loop
foreach (int i in list.GroupBy(s => s)
                  .SelectMany(grp => grp.Skip(1)))
{
   // print each element, you can do any other task on it too
   Console.WriteLine(i);
}


.. this will provide you with the only elements that are distinct. In the above context 3 and 6 were printed on screen.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900