ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

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

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!

Source

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);

Author: Dan Atkinson

Submitted on: 9 jan. 2010

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 5964