c#中Empty()和DefalutIfEmpty()用法分析
本文實例分析了c#中Empty()和DefalutIfEmpty()用法。分享給大家供大家參考。具體分析如下:
在項目中,當(dāng)我們想獲取IEnumerable<T>集合的時候,這個集合有可能是null。但通常的做法是返回一個空的集合。
假設(shè)有這樣一個場景:當(dāng)商店不營業(yè)時,返回一個空的IEnumerable<Product>,而當(dāng)商店正常營業(yè)時,就返回一個非空的IEnumerable<Product>。
Product模型。
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
該商店有一個ProductService類,該類根據(jù)屬bool類型屬性IsClosed來決定是否返回空的IEnumerable<Product>。
{
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);
}
}
在客戶端,假設(shè)我們設(shè)置為不營業(yè)。
{
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("產(chǎn)品:{0},價格:{1}",prod.Name, prod.Price);
}
}
else
{
Console.WriteLine("今天不營業(yè)~~");
}
Console.ReadKey();
}
}
輸出結(jié)果:今天不營業(yè)~~
這樣做確實沒什么問題,但問題是:當(dāng)通過 new List<Product>(0)返回空的集合時,為其分配了內(nèi)存。對于一個只讀的、空的集合類型,是否可以做到不耗費內(nèi)存呢?
--答案是使用Enumerable類的靜態(tài)方法Empty()。
在ProductService的ShowProducts()中修改如下:
{
if (!IsClosed)
{
return GetAllProducts();
}
return Enumerable.Empty<Product>();
}
輸出結(jié)果:今天不營業(yè)~~
如果在不營業(yè)的時候,我們還是想展示一些產(chǎn)品,比如把產(chǎn)品放在迎街玻璃櫥窗中展示,如何做到呢?
--這時,我們可以考慮使用Enumerable類的靜態(tài)類方法DefaultIfEmpty()。
繼續(xù)修改ProductService,添加一個返回默認IEnumerable<Product>的方法:
{
return new List<Product>()
{
new Product(){Id = 1, Name = "Product1", Price = 85M}
};
}
修改ProductService的ShowProducts()方法如下:
{
if (!IsClosed)
{
return GetAllProducts();
}
return Enumerable.DefaultIfEmpty(GetDefaultProducts());
}
總結(jié):
Empty<T>和DefaultIfEmpty(IEnumerable<T>)都是Enumerable類的靜態(tài)方法,給出了當(dāng)返回的集合類型為空時的處理方法:
● 如果想獲取一個空的集合,使用Enumerable.Empty<T>()
● 如果想給獲取到的、空的集合一個默認值,使用Enumerable.DefaultIfEmpty(IEnumerable<T>)
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C#連續(xù)任務(wù)Task.ContinueWith方法
這篇文章介紹了C#中的連續(xù)任務(wù)Task.ContinueWith方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04C#如何使用SHBrowseForFolder導(dǎo)出中文文件夾詳解
這篇文章主要給大家介紹了關(guān)于C#如何使用SHBrowseForFolder導(dǎo)出中文文件夾的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)合作工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11