I am a c# developer. I need a function to find duplicates in collection
- User
I am a c# developer. I need a function to find duplicates in collection
Assistant
Sure! Here's a C# function that can help you find duplicates in a collection:
using System; using System.Collections.Generic; public static List<T> FindDuplicates<T>(this IEnumerable<T> source) { var seen = new HashSet<T>(); var result = new List<T>(); foreach (var item in source) { if (!seen.Contains(item)) { seen.Add(item); } else { result.Add(item); } } return result; }This function uses a
HashSetto keep track of the elements in the collection that have already been seen. It then adds any duplicates to aList.Here's an example of how you can use this function:
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 6 }; var duplicates = numbers.FindDuplicates(); Console.WriteLine(duplicates); // Output: { 6 } } }In this example, the
FindDuplicatesfunction is called on a list of integers. The method returns a list of duplicates, which in this case is{ 6 }.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.