To count the number of occurrences of a certain element in a list, you can simply do:
List.Count(x => x == "Hi");
EDIT: If you just want an short-hand way of telling which element occurs N times, you could accomplish that with a nested query:
List<string> greetings = new List<string> {"Hi", "Hi", "Hello", "Hello", "Hi"};
List<string> greetingsThatOccurThreeTimes = greetings
.Where(s1 => greetings.Count(s2 => s1 == s2) == 3).ToList();
EDIT #2: You could also clean this up by using extension methods.
By declaring this:
public static class ListExtensions
{
public static List<T> WithNOccurrences<T>(this List<T> source, int n)
{
return source.Where(s1 => source.Count(s2 => s1.Equals(s2)) == n).ToList();
}
}
You could do something like this in your calling code:
List<string> greetings = new List<string> {"Hi", "Hi", "Hello", "Hello", "Hi"};
// This list will only contain "Hi" (but 3 times, though)
List<string> greetingsThatOccurThreeTimes = greetings.WithNOccurrences(3);
This should more closely resemble your "ThreeOfAKind == true".
If you only want to get back one of each item that occurs N times, simply add .Distinct()
to the extension method, like so:
public static class ListExtensions
{
public static List<T> WithNOccurrences<T>(this List<T> source, int n)
{
return source
.Where(s1 => source.Count(s2 => s1.Equals(s2)) == n)
.Distinct().ToList();
}
}