Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ find duplicates in List

Using LINQ, from a List<int>, how can I retrieve a list that contains entries repeated more than once and their values?

like image 406
Mirko Arcese Avatar asked Aug 31 '13 10:08

Mirko Arcese


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

Apa yang dimaksud dengan huruf C?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).


1 Answers

The easiest way to solve the problem is to group the elements based on their value, and then pick a representative of the group if there are more than one element in the group. In LINQ, this translates to:

var query = lst.GroupBy(x => x)               .Where(g => g.Count() > 1)               .Select(y => y.Key)               .ToList(); 

If you want to know how many times the elements are repeated, you can use:

var query = lst.GroupBy(x => x)               .Where(g => g.Count() > 1)               .Select(y => new { Element = y.Key, Counter = y.Count() })               .ToList(); 

This will return a List of an anonymous type, and each element will have the properties Element and Counter, to retrieve the information you need.

And lastly, if it's a dictionary you are looking for, you can use

var query = lst.GroupBy(x => x)               .Where(g => g.Count() > 1)               .ToDictionary(x => x.Key, y => y.Count()); 

This will return a dictionary, with your element as key, and the number of times it's repeated as value.

like image 186
Save Avatar answered Sep 26 '22 04:09

Save