None(), OneOf(), Many(), XOf()

public static class LinqExtensions
{
  public static bool None<T>(this IEnumerable<T> source)
  {
	return source.Any() == false;
  }

  public static bool None<T>(this IEnumerable<T> source, Func<T, bool> query)
  {
	return source.Any(query) == false;
  }

  public static bool Many<T>(this IEnumerable<T> source)
  {
	return source.Count() > 1;
  }

  public static bool Many<T>(this IEnumerable<T> source, Func<T, bool> query)
  {
	return source.Count(query) > 1;
  }

  public static bool OneOf<T>(this IEnumerable<T> source)
  {
	return source.Count() == 1;
  }

  public static bool OneOf<T>(this IEnumerable<T> source, Func<T, bool> query)
  {
	return source.Count(query) == 1;
  }

  public static bool XOf<T>(this IEnumerable<T> source, int count)
  {
	return source.Count() == count;
  }

  public static bool XOf<T>(this IEnumerable<T> source, Func<T, bool> query, int count)
  {
	return source.Count(query) == count;
  }
}
Example:
List<string> myList = new List<string>() { "foo", "bar", "fong", "foo" };

//returns false
myList.None();

//returns false
myList.None(x=> x == "bar");

//returns true
myList.None(x=> x == "bang");

//returns true
myList.Many();

//returns true
myList.Many(x=> x == "foo");

//returns false
myList.Many(x=> x == "bar");

//returns false
myList.OneOf();

//returns false
myList.OneOf(x=> x == "foo");

//returns true
myList.OneOf(x=> x == "bar");

//returns true
myList.Xof(4);

//returns true
myList.XOf(x=> x == "foo", 2);

//returns false
myList.XOf(x=> x == "foo", 3);

Description

Count-based extensions which make checking the length of something more readable. * Updated on 2010-01-16 following suggestion from @Sane regarding the use of Count() in None(). Switched to Any(). Thanks!

Details

Double click on the code to select all.

 

;