anm*_*rti 0 c# generics ienumerable generic-collections
我想创建一个IEnumerable类的扩展方法,并创建一个方法来检索集合中不是string.empty的最后一项.集合将始终是一个数组,返回的值是一个字符串.
我认为空值为空字符串.
我不知道如何以泛型方式执行此操作.我想知道我是否应该将它作为通用方法,因为类型将是一个字符串数组.
我会像这样调用这个函数:
string s = myArray.LastNotEmpty<???>();
Run Code Online (Sandbox Code Playgroud)
我怎么能面对这个?
static class Enumerable
{
public static TSource LastNotEmpty<TSource>(this IEnumerable<TSource> source)
{
}
}
Run Code Online (Sandbox Code Playgroud)
static class MyEnumerable
{
public static TSource LastNotEmpty<TSource>(this IEnumerable<TSource> source) where TSource:String
{
return source.LastOrDefault(x=>!string.isNullOrEmpty(x));
}
}
Run Code Online (Sandbox Code Playgroud)
或更具体
static class MyEnumerable
{
public static string LastNotEmpty(this IEnumerable<string> source)
{
return source.LastOrDefault(x=>!string.isNullOrEmpty(x));
}
}
Run Code Online (Sandbox Code Playgroud)
如其他答案中所述,Enumerable已存在于System.Linq命名空间中,因此静态类在此处的命名方式不同.
然后,您只需确保您的调用代码具有using
该类的命名空间,然后使用
string s = myArray.LastNotEmpty();
Run Code Online (Sandbox Code Playgroud)
s
如果没有出现,则将等于null.
LastNotEmpty的任一实现都可以使用上述调用方法,因为编译器可以解决GenericType的问题.
不需要此行下面的更新来回答它们作为更通用方法的替代解决方案提供的问题
更新 - 只是为了取悦谁想要一个完全通用的解决方案.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);
}
}
Run Code Online (Sandbox Code Playgroud)
这将首先将集合过滤为string类型的集合.结果将是null
集合为null或没有找到结果.
再次更新 - 这只是尝试使递归感觉良好:)
此版本将返回第一个TSource
不等于空字符串或null的版本.使用它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)
);
}
}
Run Code Online (Sandbox Code Playgroud)