簡體   English   中英

當包含值時,為什么Contains(value)等於false?

[英]Why does the Contains(value) equal false when it contains the value?

這是數據,一個字符數組(板)和一個字符數組列表,這些字符數組與板中的三個字符序列不同。

public static char[] board = { 'Q', '-', '+',
                               'A', '-', 'D',
                               '+', 'X', 'C' };

static List<char[]> dalist = new List<char[]> { 
        new char[3] { board[3], board[4], board[5] },
        new char[3] { board[0], board[4], board[8] },
        new char[3] { board[2], board[4], board[6] },
        new char[3] { board[1], board[4], board[7] },

        new char[3] { board[0], board[1], board[2] },
        new char[3] { board[6], board[7], board[8] },
        new char[3] { board[0], board[3], board[6] },
        new char[3] { board[2], board[5], board[8] }
};

static void Main(){   

    foreach (var item in dalist[2])
    {
        Console.WriteLine(item);
    }
    // This returns + - + as expected


    Console.WriteLine(dalist[2].ToString().Contains("-"));
    // This returns false

}

為什么.Contains方法意外返回false?

daList[2]char[] 當您在數組上調用ToString()時,它不會將數組的所有元素連接成字符串,而是返回類名,在本例中為System.Char[] 如果執行Console.WriteLine(daList[2].ToString())則可以自己查看。 由於文字字符串"System.Char[]"不包含連字符,因此daList[2].ToString().Contains("-")返回false。

如果要從字符數組創建字符串,則可以使用字符串構造函數。 我認為這是您真正想要的:

Console.WriteLine(new String(dalist[2]).Contains("-"));

小提琴: https : //dotnetfiddle.net/jLpJLV

你可以簡單地檢查是否datalist2 contains的字符-通過使用Containsarray

Console.WriteLine(dalist[2].Contains('-'));

您的dataList不是字符數組,而是數組列表。 因此,您需要的是第三列表中的第二個元素,或[2] [1]中的元素。 所以你需要這個:

Console.WriteLine(datalist[2][1].ToString().Contains("-"));

可以進一步簡化為

Console.WriteLine(datalist[2][1] == '-');

另一種方法是檢查列表是否包含字符:

Console.WriteLine(datalist[2].Contains('-'));

為什么您的方法行不通的原因在於,當在字符數組上調用ToString時,它不會簡單地組合字符,而是創建類似於System.Char[]東西,這顯然不是您期望的。 ToString方法不夠聰明,無法首先檢查其中的元素並在那里使用字符串表示形式。 但是,它只是返回其包含元素的類型。

dalist[2]不是單個值,它是char數組,當您在char數組上調用ToString() ,會得到“ System.Char[] ”而不是您想的那樣的“ +-+”。

Console.WriteLine(dalist[2][1].ToString().Contains("-"));
// This will returns true

如果要檢查數組中是否存在某項,請刪除ToString()並查找該字符。

Console.WriteLine(dalist[2].Contains('-'));

這一項檢查“ System.Char []”是否包含“-”並且結果為FALSE

Console.WriteLine(dalist[2].ToString().Contains('-'));

這一項檢查[“ +”] [“-”] [“ +”]是否包含“-”並且結果為TRUE

Console.WriteLine(dalist[2].Contains('-'));
string dalist2 = dalist[2][0].ToString() + dalist[2][1].ToString() + dalist[2][2].ToString();

Console.WriteLine(dalist2.Contains("-"));

要么

Console.WriteLine(dalist[2].Contains('-'));

將您的代碼從.ToString().ToList()即如下更改代碼

bool isContains = dalist[2].ToList().Contains('-');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM