扩展IEnumerable:如何返回最后一个not-string.empty元素



我想创建一个类IEnumerable的扩展方法,并创建一个方法来检索集合中不是字符串的最后一个项。empty。集合将始终是数组,返回值为字符串。

我认为空值是一个空字符串。

我不知道如何用泛型的方式来做这件事。我想知道我是否应该将其作为一个泛型方法,因为类型将是一个字符串数组。

我会这样调用这个函数:

string s = myArray.LastNotEmpty<???>();

我该如何面对?

static class Enumerable
{
public static TSource LastNotEmpty<TSource>(this IEnumerable<TSource> source)
{
}
}
static class MyEnumerable
{
public static TSource LastNotEmpty<TSource>(this IEnumerable<TSource> source) where TSource:String
{
return source.LastOrDefault(x=>!string.isNullOrEmpty(x));
}
}

或更具体的

static class MyEnumerable
{
public static string LastNotEmpty(this IEnumerable<string> source) 
{
return source.LastOrDefault(x=>!string.isNullOrEmpty(x));
}
}

正如其他答案中所述,Enumerable已经存在于System.Linq命名空间中,因此静态类在这里的命名有所不同。

然后,您只需确保您的调用代码具有该类命名空间的using,然后只使用

string s = myArray.LastNotEmpty();

如果没有出现,则s将等于null。

上面的调用方法可以由LastNotEmpty的任何一个实现使用,因为GenericType分段可以由编译器计算出来。

这行下面的更新不需要回答问题,它们只是作为更通用方法的替代解决方案提供的

更新-只是为了取悦Recursive谁想要一个完全通用的解决方案。OP已经声明集合将始终是字符串,但是

static class MyEnumerable {
public static string LastNotEmpty<TSource>(this IEnumerable<TSource> source) {
if (source==null) return null;  // Deals with null collection
return source.OfType<string>().LastOrDefault(x=>!string.IsNullOrEmpty(x);
}
}

这将首先将集合筛选为字符串类型的集合。如果集合为null或找不到结果,则结果将为null。。

再次更新-这只是为了让递归感觉良好:)

此版本将返回第一个不等于空字符串或null的TSource。之所以使用ReferenceEquals,是因为resharper抱怨将可能的值类型与null进行比较。。。

static class MyEnumerable {
public static TSource LastNotEmpty<TSource>(this IEnumerable<TSource> source) {
if (source==null) return null;  // Deals with null collection
return source.LasdtOrDefault(x=>
!ReferenceEquals(x,null)
&&
!x.Equals(String.Empty)
);
}
}

假设您有一个IEnumerable<string>,您可以直接调用

string lastNotEmpty = myIEnumerableString.Last(s => !String.IsNullOrEmpty(s));

就像这里一样。

相关内容

最新更新