single value enumerable

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;

public class Program {
	
	public static IEnumerable<T> ToEnumerable1 <T> (T v) {
		yield return v;
	}
	
	public static T[] ToEnumerable2 <T> (params T[] vs) => vs;
	
	public static void Main () {
		static IEnumerable<T> ToEnumerable3 <T> (params T[] v) => v;
		p( new string[] { "three" } );
		p( new List<string> { "three" } );
		p( ToEnumerable1("three") ); // our utility function (yield return)
		p( ToEnumerable2("three") ); // our utility function (params)
		p( ToEnumerable3("three") ); // our local utility function (params)
		p( Enumerable.Empty<string>().Append("three") );
		p( Enumerable.Empty<string>().DefaultIfEmpty("three") );
		p( Enumerable.Empty<string>().Prepend("three") );
		p( Enumerable.Range(3, 1) ); // only for int
		p( Enumerable.Range(0, 1).Select(_ => "three") );
		p( Enumerable.Repeat("three", 1) );
		p( "_".Select(_ => "three") ); // doesn't have to be "_"; just any one character
		p( "_".Select(_ => 3.3333) );
		p( from _ in "_" select 3.0f );
		p( "a" ); // only for char
		// these weren't available for me to test (might not even be valid):
		//   new Microsoft.Extensions.Primitives.StringValues("three")
		
	}

	static void p <T> (IEnumerable<T> e) =>
		Console.WriteLine(string.Join(' ', e.Select((v, k) => $"[{k}]={v,-8}:{v.GetType()}").DefaultIfEmpty("<empty>")));

}
;