65.9K
CodeProject 正在变化。 阅读更多。
Home

我期望的FirstOrDefault扩展方法

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (3投票s)

2010年11月8日

CPOL

1分钟阅读

viewsIcon

39356

downloadIcon

108

创建一个将默认值作为参数的FirstOrDefault扩展方法

引言

在本文中,我将展示如何为 IEnumerable 集合创建和使用扩展方法。

背景

每当我需要从列表中提取特定对象时,我总是会编写相同的代码来检查该项目是否存在于集合中,如果存在则返回该项目,否则返回默认值。

if (stateList.Count(x => x.Code == "ME") > 0)
{
    Console.WriteLine(stateList.FirstOrDefault(x => x.Code == "ME", defaultState).Name);
}
else
{
    Console.WriteLine(defaultState.Name);
}

解决方案

IEnumerable 已经有一个 FirstOrDefault 方法,但它并没有像我期望的那样工作。我期望能够传入我想要在没有满足条件的项时返回的默认值。

第一步是创建一个 static 类来保存扩展方法。

namespace FirstOrDefaultExtension.IEnumerableExtensionMethods
{
    internal static class IEnumerableExtensionMethods
    {
    }
} 

接下来,你定义扩展方法。该方法必须是 static 的。

public static TSource FirstOrDefault3<TSource>
  (this IEnumerable<TSource> enumerable, Func<TSource, bool> pred, TSource defaultValue)
{
	foreach (var x in enumerable.Where(pred))
	{
		return x;
	}
	return defaultValue;
}  

(感谢 Dimzon 提供了此方法的核心部分,该方法性能良好,我第一次尝试的作品,但性能不佳。)

可枚举参数是该方法将作用的 IEnumerable 集合。通过这样定义,我们表明此方法将作为实现 IEnumerable 的类的扩展方法可用。 TSource 是集合中对象的类型,并且在这种情况下,我们返回该类型的对象。

使用代码很简单,这很好,因为简单性是代码的全部意义。

var stateList = new List<State>();

stateList.Add(new State("ME", "Maine"));
stateList.Add(new State("NH", "New Hampshire"));
stateList.Add(new State("VT", "Vermont"));
stateList.Add(new State("MA", "Massachusetts"));
stateList.Add(new State("RI", "Rhode Island"));
stateList.Add(new State("CT", "Connecticut"));

var defaultState = new State("", "Non New England State Code");

Console.WriteLine(stateList.FirstOrDefault(x => x.Code == "ME", defaultState).Name);
Console.WriteLine(stateList.FirstOrDefault(x => x.Code == "NY", defaultState).Name); 

此代码的输出将是

Maine 

Non New England State Code 

历史

  • 2010/11/08 - v1 首次发布
  • 2010/11/08 - v2 修复了文章评论中指出的性能问题
© . All rights reserved.