Enumerable.Empty和Enumerable.DefaultIfEmpty
class Program { static void Main(string[] args) { var noEmployeeList = GetIEnumerable(); foreach (var emp in noEmployeeList) { Console.WriteLine(emp); } Console.Read(); } static IEnumerable<Employee> GetIEnumerable() { if (IsOnActive()) { return new List<Employee> { new Employee() { Id = 1, Name = "zs", Salary = 10000 } }; } // 比new List<Empolyee>()节省内存。 return Enumerable.Empty<Employee>(); } static bool IsOnActive() { return false; } } public sealed class Employee { public long Id { get; set; } public string Name { get; set; } public double Salary { get; set; } public override string ToString() { return string.Format("ID:{0},Name:{1},Salary:{2}", Id, Name, Salary); } }
转载自http://www.cnblogs.com/multiplesoftware/archive/2011/06/04/2072415.html
------ 20220303
IEnumerable<string> enumerable = Enumerable.Empty<string>(); int c = enumerable.Count(); Console.WriteLine(c); IEnumerable<string> enumOne = Enumerable.DefaultIfEmpty<string>(enumerable); c = enumOne.Count(); Console.WriteLine(c); foreach (var s in enumOne) { Console.WriteLine(string.IsNullOrEmpty(s)); } IEnumerable<string> enumoned = Enumerable.DefaultIfEmpty(enumerable, "SUM"); Console.WriteLine(enumoned.Count()); foreach (var s in enumoned) { Console.WriteLine(s); }