How do you check if a collection contains duplicates?
4 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Rajanikant HawaldarRank #110 · 20.2K reputationPosted Sep 25, 2022, 12:44 AM EDT
better don't allow to add duplicates, there is 'contains' utilize it or use collection which doesn't allow duplicates
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Sep 24, 2022, 7:35 AM EDT
You can try the following code to check wheather a collection have duplicate value or not.
var yourList = new List(); yourList.Add(1); yourList.Add(2); yourList.Add(3); yourList.Add(1); if (yourList.Count != yourList.Distinct().Count()) { // duplicates values exist in list }Sachin SinghRank #66 · 26.2K reputationPosted Sep 24, 2022, 7:53 AM EDT
bool isAnyDuplicate=YourList.GroupBy(x =>x.Name).Any(c => c.Count() > 1); //Name is property in your classfor complex type use group by as Distinct won't work without IComparer implementation
Vishal YelveRank #178 · 13.6K reputationPosted Sep 25, 2022, 1:11 AM EDT
var query = lst.GroupBy(x => x) .Where(g => g.Count() > 1) .Select(y => y.Key) .ToList();