public static void TrimDnsCache() { var countBeforeTrim = Dns.Count; var tenth = countBeforeTrim / 10; //remove the ones with expired dates first foreach (var item in Dns.Where(x => x.Value.ExpireDate < DateTime.Now).ToList()) { Dns.Remove(item.Key); } if (Dns.Count != countBeforeTrim) { Console.WriteLine($"Removed {countBeforeTrim - Dns.Count} expired dns"); } //if cache is still quite full, then trim a little more var rest = tenth - (countBeforeTrim - Dns.Count); if (rest < 0) { return; } foreach (var item in Dns.Take(rest).ToList()) { Dns.Remove(item.Key); } Console.WriteLine("Trimming DNS to 9 tenths"); }