Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 查找字符串数组逗号分隔的字符串列表_C#_Arrays_String - Fatal编程技术网

C# 查找字符串数组逗号分隔的字符串列表

C# 查找字符串数组逗号分隔的字符串列表,c#,arrays,string,C#,Arrays,String,查找字符串数组逗号分隔的字符串列表的最佳方法是什么?下面是我的示例,我一直得到false const string _select_records = ("show all records, show invalid records, show valid records" ); bool flag = _select_records.Split(',').Contains("show all records"); 这应该对你有用 var stringToCheck = "show all

查找字符串数组逗号分隔的字符串列表的最佳方法是什么?下面是我的示例,我一直得到
false

const string _select_records = ("show all records, show invalid records, show valid records" );

bool flag = _select_records.Split(',').Contains("show all records");

这应该对你有用

var stringToCheck = "show all records";
bool flag = _select_records.Split(',').Any(stringToCheck.Contains))

您所拥有的也应该可以使用。

此行
bool flag=\u select\u records.Split(',')。包含(“显示无效记录”)
返回false,因为由
Split
返回的数组将返回三个元素,并且由于第二个和第三个元素在分隔符之前有空格,所以数组中的值如下所示:

"show all records" //no leading space
" show invalid records" // one leading space
" show valid records" // one leading space
现在该检查
。包含(“显示无效记录”)
应用于字符串数组,因此它将查找精确值为“show invalid records”的数组元素,不带前导空格。由于没有与精确值匹配的数组元素,因此返回false

有多种方法可以解决此问题,最简单的方法是使用
Trim
删除尾随空格和前导空格,然后应用
Contains
如下:

bool flag = _select_records.Split(',').Select(s=> s.Trim())
                           .Contains("show invalid records");

它返回
true
,我无法复制它。没有
Split()
子句,逻辑不一样吗?为什么是downvote?想解释一下原因吗?@Habib:我不确定你是如何得到正确答案的,或者像我所展示的那样从初始值中删除它,或者像@Habib在他的回答中指出的那样,修剪选择。他的解决方案的优点是避免了猜测存在多少前导/尾随空格的风险——例如,如果您无法控制逗号分隔的字符串。