[英]Is there a better way to write new List<string> {“a”, “b”}.Contains(str)?
我想測試短字符串列表中是否包含某個字符串。 當前的代碼是這樣的:
if (new List<string> { "A", "B", "C" }.Contains (str)) {
但是,這似乎是ated腫的。 例如,iirc,在Java中,我可以簡單地編寫{"A", "B", "C"}.Contains(str)
,比上面的代碼更好。
我確信C#中有更好的方法。 你能指出嗎?
我想您可以將其縮短為:
if ((new []{ "A", "B", "C" }).Contains (str)) {
不知道它會產生多少實際差異。
更新:如果您知道要測試一個字母,我認為沒有理由列出它或列表:
if ("ABC".Contains(str)) {
該代碼既短又快。 但話又說回來,我想單字母字符串只是示例...
您可以編寫一個擴展方法:
public static bool In<T>(this T obj, params T[] candidates)
{
return obj.In((IEnumerable<T>)candidates);
}
public static bool In<T>(this T obj, IEnumerable<T> candidates)
{
if(obj == null) throw new ArgumentNullException("obj");
return (candidates ?? Enumerable.Empty<T>()).Contains(obj);
}
然后可以用來執行以下操作:
if(str.In("A", "B", "C")) { ... }
那么這種方法呢:
"A;B;C".Split(';').Contains(str);
如果簡短的字符串列表是恆定的,則應使用靜態只讀字符串數組。
好處是它很容易編寫,並且每次執行檢查時都不會實例化新的List。
private static readonly string[] Names = new string[] { "A", "B", "C" };
...
if (Names.Contains(str)) {
但是,該解決方案不可擴展,因為搜索是以線性方式完成的。 另外,您可以按排序的方式定義常量數組,並對數組使用BinarySearch。
// this has to be sorted
private static readonly string[] Names = new string[] { "A", "B", "C" };
...
if (Array.BinarySearch(Names, str) >= 0) {
要完全更改它:
switch(str){
case "A":
case "B":
case "C":
contains = true;
break;
default:
contains = false;
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.