C# 字符串在数组中吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/501194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is string in array?
提问by Brad
What would be the best way to look in a string[]
to see if it contains a element. This was my first shot at it. But perhaps there is something that I am overlooking. The array size will be no larger than 200 elements.
查看 astring[]
是否包含元素的最佳方法是什么。这是我第一次尝试。但也许我忽略了一些东西。数组大小不超过 200 个元素。
bool isStringInArray(string[] strArray, string key)
{
for (int i = 0; i <= strArray.Length - 1; i++)
if (strArray[i] == key)
return true;
return false;
}
采纳答案by Dave Markle
Just use the already built-in Contains() method:
只需使用已经内置的 Contains() 方法:
using System.Linq;
//...
string[] array = { "foo", "bar" };
if (array.Contains("foo")) {
//...
}
回答by masfenix
You can also use LINQ to iterate over the array. or you can use the Find method which takes a delegate to search for it. However I think the find method is a bit more expensive then just looping through.
您还可以使用 LINQ 遍历数组。或者您可以使用 Find 方法,它需要一个委托来搜索它。但是我认为 find 方法比循环遍历要贵一些。
回答by Andrew Hare
Is the array sorted? If so you could do a binary search. Here is the .NET implementation as well.If the array is sorted then a binary search will improve performance over any iterative solution.
数组是否排序?如果是这样,您可以进行二分搜索。这里也是.NET 实现。如果数组已排序,则二进制搜索将提高任何迭代解决方案的性能。
回答by Noldorin
You're simply after the Array.Exists function (or the Contains extension method if you're using .NET 3.5, which is slightly more convenient).
您只是在 Array.Exists 函数(或如果您使用的是更方便的 .NET 3.5 的 Contains 扩展方法)之后。
回答by Noldorin
Linq (for s&g's):
Linq(适用于 s&g):
var test = "This is the string I'm looking for";
var found = strArray.Any(x=>x == test);
or, depending on requirements
或者,根据要求
var found = strArray.Any(
x=>x.Equals(test, StringComparison.OrdinalIgnoreCase));
回答by Chris Ballance
This is quicker than iterating through the array manually:
这比手动遍历数组更快:
static bool isStringInArray(string[] strArray, string key)
{
if (strArray.Contains(key))
return true;
return false;
}
回答by Zack Elan
Arrays are, in general, a poor data structure to use if you want to ask if a particular object is in the collection or not.
如果您想询问特定对象是否在集合中,数组通常是一种糟糕的数据结构。
If you'll be running this search frequently, it might be worth it to use a Dictionary<string, something>
rather than an array. Lookups in a Dictionary are O(1) (constant-time), while searching through the array is O(N) (takes time proportional to the length of the array).
如果您将频繁运行此搜索,则使用 aDictionary<string, something>
而不是数组可能是值得的。字典中的查找是 O(1)(恒定时间),而在数组中搜索是 O(N)(花费的时间与数组的长度成正比)。
Even if the array is only 200 items at most, if you do a lot of these searches, the Dictionary will likely be faster.
即使数组最多只有 200 个项目,如果您进行大量此类搜索,Dictionary 可能会更快。
回答by Dave
As mentioned many times in the thread above, it's dependent on the framework in use. .Net Framework 3 and above has the .Contains() or Exists() methods for arrays. For other frameworks below, can do the following trick instead of looping through array...
正如在上面的线程中多次提到的,它依赖于使用的框架。.Net Framework 3 及更高版本具有用于数组的 .Contains() 或 Exists() 方法。对于下面的其他框架,可以执行以下技巧而不是遍历数组...
((IList<string>)"Your String Array Here").Contains("Your Search String Here")
Not too sure on efficiency... Dave
不太确定效率...戴夫
回答by Gabriel McAdams
I know this is old, but I wanted the new readers to know that there is a new method to do this using generics and extension methods.
我知道这是旧的,但我想让新读者知道有一种新方法可以使用泛型和扩展方法来做到这一点。
You can read my blog postto see more information about how to do this, but the main idea is this:
您可以阅读我的博客文章以了解有关如何执行此操作的更多信息,但主要思想是:
By adding this extension method to your code:
通过将此扩展方法添加到您的代码中:
public static bool IsIn<T>(this T source, params T[] values)
{
return values.Contains(source);
}
you can perform your search like this:
您可以像这样执行搜索:
string myStr = "str3";
bool found = myStr.IsIn("str1", "str2", "str3", "str4");
It works on any type (as long as you create a good equals method). Any value type for sure.
它适用于任何类型(只要您创建了一个好的 equals 方法)。任何值类型都是肯定的。
回答by mateiasu
If you don't want to or simply can't use Linq you can also use the static Array.Exists(...);
function:
如果您不想或根本不能使用 Linq,您也可以使用静态Array.Exists(...);
函数:
https://msdn.microsoft.com/en-us/library/yw84x8be%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
https://msdn.microsoft.com/en-us/library/yw84x8be%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
var arr = new string[]{"bird","foo","cat","dog"};
var catInside = Array.Exists(
arr, // your Array
(s)=>{ return s == "cat"; } // the Predicate
);
When the Predicate do return true once catInside will be true as well.
当谓词确实返回 true 时,catInside 也会为 true。