要计算列表中某个元素的出现次数,您可以简单地执行以下操作:
List.Count(x => x == "Hi");
编辑:如果您只是想要一种简单的方法来判断哪个元素出现 N 次,您可以使用嵌套查询来完成:
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:您也可以使用扩展方法来清理它。
通过声明:
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();
}
}
你可以在你的调用代码中做这样的事情:
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);
这应该更类似于您的“ThreeOfAKind == true”。
如果您只想取回每个出现 N 次的项目之一,只需将 .Distinct() 添加到扩展方法中,如下所示:
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();
}
}