Skip to content

Instantly share code, notes, and snippets.

@justinAurand
Last active December 21, 2015 23:29
Show Gist options
  • Save justinAurand/6382488 to your computer and use it in GitHub Desktop.
Save justinAurand/6382488 to your computer and use it in GitHub Desktop.
Find and return first duplicate in a generic list.
using System;
using System.Collections.Generic;
using System.Collections;
class FindFirstDuplicate
{
public static void Main()
{
var input = new List<string> { "Foo", "Bar", "Bar", "Foo" };
object result = GetFirstDuplicateValue(input);
PrintDuplicateResult(result);
var input2 = new List<int> { 0, 1, 2, 3, 12, 11, 112 };
object result2 = GetFirstDuplicateValue(input2);
PrintDuplicateResult(result2);
Console.ReadKey();
}
public static object GetFirstDuplicateValue<T>(List<T> input)
{
var hash = new Hashtable();
foreach (object listItem in input)
{
if (hash.ContainsKey(listItem))
{
var value = (Int32)hash[listItem];
hash[listItem] = value + 1;
}
else
hash.Add(listItem, 1);
}
foreach (object listItem in input)
if ((Int32)hash[listItem] > 1)
return (listItem);
return null;
}
public static void PrintDuplicateResult(object input)
{
Console.WriteLine((input != null) ? input.ToString() : "No Duplicates.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment