按特定字符串筛选数组项



我是C#的新手,我一直在尝试制作一个简单的方法,该方法应该使用字符串数组和前缀,然后根据前缀过滤数组项。

基本上,如果我将类似string[] data = "A horse, or a HORSE!!!".Split(' ');的数组传递给它,那么如果前缀="0",它应该返回{"horse,","HORSE!!!"};马";。当然,如果传递了一个空字符串前缀,它应该返回每个项。我想我自己也差点把事情做好,但现在我碰壁了。

我还希望它在prefix=null时返回ArgumentIsNull异常。但奇怪的是,它就是不想触发!我进行了测试,当没有foreach循环时抛出异常,但foreach没有。为什么它会那样?

using System;
using System.Collections.Generic;
using System.Linq;
namespace Enumerable
{
public class EnumerableManipulation
{
public IEnumerable<string> GetPrefixItems(IEnumerable<string> data, string prefix)
{
if (prefix == null) 
{
throw new ArgumentNullException(); 
} 
///Why does this exception never trigger when I pass a null prefix? But it works if there is no foreach.
foreach (string item in data)
{
///I thought this would do the trick and now I can't figure out why it doesn't work
if (data.All(prefix.Contains))
{
yield return item;
}
}
}
}
}

它是一个枚举。只有当您实际枚举函数的结果时,您的所有代码(包括在yield之前发生的事情(才会被执行。通过调用.ToList((或foreach循环。

如果你这样做:

var result = GetPrefixItems(..., null).ToList() 

它应该给你一个例外。

如果您不需要产生输出,那么您可以使用Linq来过滤您的数组,如下所示:

IEnumerable<string> data = "A horse, or a HORSE!!!".Split(' ');
IEnumerable<string> result = data.Where(x => x.Contains("horse"));

最新更新