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

To

Allows enumaration of sets of characters by expressing them as a range, for example all the lowercase characters. Allows reverse order as well.

Source

public static class EnumerableExtensions
	{
		private static void Swap(ref char a, ref char b)
		{
			a ^= b;
			b ^= a;
			a ^= b;
		}

		public static IEnumerable<char> To(this char first, char last)
		{
			bool reverseRequired = (first > last);

			if (reverseRequired)
				Swap(ref first, ref last);

			var result = Enumerable.Range(first, last - first + 1).Select(charCode => (char)charCode);

			if (reverseRequired)
				result = result.Reverse();

			return result;
		}
	}

Example

foreach (char c in 'a'.To('z'))
				Console.WriteLine(c);
			foreach (char c in '0'.To('9'))
				Console.WriteLine(c);

Author: Figment Engine

Submitted on: 6 feb 2009

Language: C#

Type: System.Char

Views: 2688