在项目中,当我们想获取IEnumerable<T>集合的时候,这个集合有可能是null。但通常的做法是返回一个空的集合。

假设有这样一个场景:当商店不营业时,返回一个空的IEnumerable<Product>,而当商店正常营业时,就返回一个非空的IEnumerable<Product>。

Product模型。

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

该商店有一个ProductService类,该类根据属bool类型属性IsClosed来决定是否返回空的IEnumerable<Product>。

public class ProductService
{
public bool IsClosed { get; set; } private static IEnumerable<Product> GetAllProducts()
{
return new List<Product>()
{
new Product(){Id = 1, Name = "Product1", Price = 85M},
new Product(){Id = 2, Name = "Product2", Price = 90M}
};
} public IEnumerable<Product> ShowProducts()
{
if (!IsClosed)
{
return GetAllProducts();
}
return new List<Product>(0);
}
}

在客户端,假设我们设置为不营业。

class Program
{
static void Main(string[] args)
{
ProductService service = new ProductService();
service.IsClosed = true; IEnumerable<Product> products = service.ShowProducts();
if (products.Count() > 0)
{
foreach (var prod in products)
{
Console.WriteLine("产品:{0},价格:{1}",prod.Name, prod.Price);
}
}
else
{
Console.WriteLine("今天不营业~~");
}
Console.ReadKey();
}
}

输出结果:今天不营业~~

这样做确实没什么问题,但问题是:当通过 new List<Product>(0)返回空的集合时,为其分配了内存。对于一个只读的、空的集合类型,是否可以做到不耗费内存呢?

--答案是使用Enumerable类的静态方法Empty()。

在ProductService的ShowProducts()中修改如下:
public IEnumerable<Product> ShowProducts()
{
if (!IsClosed)
{
return GetAllProducts();
}
return Enumerable.Empty<Product>();
}

输出结果:今天不营业~~

如果在不营业的时候,我们还是想展示一些产品,比如把产品放在迎街玻璃橱窗中展示,如何做到呢?

--这时,我们可以考虑使用Enumerable类的静态类方法DefaultIfEmpty()。

继续修改ProductService,添加一个返回默认IEnumerable<Product>的方法:

private static IEnumerable<Product> GetDefaultProducts()
{
return new List<Product>()
{
new Product(){Id = 1, Name = "Product1", Price = 85M}
};
}

修改ProductService的ShowProducts()方法如下:

public IEnumerable<Product> ShowProducts()
{
if (!IsClosed)
{
return GetAllProducts();
}
return Enumerable.DefaultIfEmpty(GetDefaultProducts());
}

总结

Empty<T>和DefaultIfEmpty(IEnumerable<T>)都是Enumerable类的静态方法,给出了当返回的集合类型为空时的处理方法:

● 如果想获取一个空的集合,使用Enumerable.Empty<T>()
● 如果想给获取到的、空的集合一个默认值,使用Enumerable.DefaultIfEmpty(IEnumerable<T>)

c#中何时使用Empty()和DefalutIfEmpty()的更多相关文章

  1. php中函数 isset(), empty(), is_null() 的区别,boolean类型和string类型的false判断

    php中函数 isset(), empty(), is_null() 的区别,boolean类型和string类型的false判断 实际需求:把sphinx返回的结果放到ssdb缓存里,要考虑到sph ...

  2. String中的==与Empty

    1.String中的==与Equals方法执行结果一样吗? 我们都知道对于引用类型"=="比较的是引用而不是具体的值,但c#中有一种神奇的叫做操作符重载的东西.官方对String类 ...

  3. PHP中isset和empty的区别(最后总结)

    PHP的isset()函数 一般用来检测变量是否设置 格式:bool isset ( mixed var [, mixed var [, ...]] ) 功能:检测变量是否设置 返回值: 若变量不存在 ...

  4. jQuery中删除方法empty(),remove()和detach()的区别

    empty():清空匹配的元素集合中所有的子节点,自身节点和事件都未被删除. remove():这个方法不会把匹配的元素从jQuery对象中删除,因而可以在将来再使用这些匹配的元素.但除了这个元素本身 ...

  5. jQuery中清空元素.empty()和.html(''),两种方法的对比

    jQuery 中有 .empty() 和 .html() 两种方式,都能够清空所选父元素中的所有子元素.但是这两者清空元素的方式上,有着很大的区别: 1.empty() jQuery对象.empty( ...

  6. EL表达式中null和empty的区别

    下面通过一个例子看看看null和empty的区别,建立一个test.jsp文件,内容如下: <%@page pageEncoding="utf-8" %> name:$ ...

  7. jQuery中detach&&remove&&empty三种方法的区别

    jQuery中empty&&remove&&detach三种方法的区别 empty():移除指定元素内部的所有内容,但不包括它本身 remove():移除指定元素内部的 ...

  8. php中函数 isset(), empty(), is_null() 的区别

    NULL:当你在你的脚本中写下这样一行代码 $myvariable; //此处你想定义一个变量,但未赋值.会有Notice: Undefined variable echo $myvariable + ...

  9. php 中 isset 和empty 的区别

    昨天终于开始学习php了,这个对于我来说听着很熟悉,但是学起来很陌生的东西,尤其是课上能听明白 但是真正写起了手生,都不知道手该往哪里放了,天哪~~~ 其中课上有讲到 isset和empty的区别,现 ...

随机推荐

  1. HDU 2609 How many(最小表示+set)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2609 题目大意: 题目大意有n个有01组成的字符串,每个字符串都代表一个项链,那么该字符串就是一个环状 ...

  2. NopCommerce Plugins 不能智能提示的解决方法(MVC 5 & RAZOR 3.0)

    分享给需要的朋友: http://mhammadchehab.com/wordpress/2013/12/enabling-intellisense-for-razor-in-class-librar ...

  3. python连接hbase

    安装HBase HBase是一个构建在HDFS上的分布式列存储系统,主要用于海量结构化数据存储.这里,我们的目标只是为Python访问HBase提供一个基本的环境,故直接下载二进制包,采用单机安装.下 ...

  4. Python3语法详解

    一.下载安装 1.1Python下载 Python官网:https://www.python.org/ 1.2Python安装 1.2.1 Linux 平台安装 以下为在Unix & Linu ...

  5. 安装配置SVN

    官网下载地址,下载完之后如果想看到中文,可以下载语言包进行安装,安装之后TortoiseSVN -> Settings -> General -> Language选项中选择:中文( ...

  6. USACO 6.5 Closed Fences

    Closed Fences A closed fence in the plane is a set of non-crossing, connected line segments with N c ...

  7. too many open file /etc/security/limits.conf

      当出现too mang open file 时更改/etc/profile中的ulimit -n 65536 ,查看   然后ssh进去,或者退出之后重新登录使之生效                ...

  8. 007 爬虫(Scrapy库的使用)

    推荐网址: http://scrapy-chs.readthedocs.io/zh_CN/0.24/topics/architecture.html 1.简介 python开发的一个快速,高层次的屏幕 ...

  9. 005 爬虫(requests与beautifulSoup库的使用)

    一:知识点 1.安装requests库 2.Brautiful soup 可以提供一些简单的,python式的函数来处理导航,搜索,修改分析树等功能. 她是一个工具箱,通过解析文档为用户提供需要抓去的 ...

  10. ecshop,大商创后台设置增加字段方法

    使用场景:在开发过程中有时是需要在后台增加一个参数 例如: 必须要改数据库和源码的 1,在数据库中增加一条数据 数据库名称:shop_config 2:后台语言包