我正在尝试在文件中查找状态的子字符串。我打开文件并一次加载每一行字符串。然后我想检查每个字符串是否包含我的子字符串中的一个状态。它没有按预期工作,因为它不断返回"找不到子串"即使我知道状态在字符串中。我做错了什么?
编辑:我现在意识到错误,这条线是完全错误的:if (lines.Any(stringToCheck.Contains))
应该是这样的:
if (stringToCheck.Any(s.Contains))
感谢帮助人员。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
class Program
{
static void Main (string[] args)
{
string[] stringToCheck = {"Alabama","Alaska","Arizona","Arkansas","California","Colorado"};
string[] lines = File.ReadAllLines(@"C:\C# Project\sampledata.dat");
foreach (string s in lines)
{
if (lines.Any(stringToCheck.Contains))
{
Console.WriteLine("Found substring");
Console.WriteLine(s);
Console.ReadLine();
}
else
Console.WriteLine("Could not find substring");
Console.WriteLine(s);
Console.ReadLine() ;
}
}
}
}
答案 0 :(得分:3)
您可以在状态列表上使用Any
来检查该行包含的每个州是否有任何字符串。样本:
if (stringToCheck.Any(x = > s.Contains(x))
{
// ...
}
答案 1 :(得分:0)
as ct(...)
答案 2 :(得分:0)
你可以这样做:
string[] stringToCheck = { "Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado" };
//Some test lines
string[] lines = { "sadnaskjd Alabama", "sadasd Arizona", "asdasdaer" };
//A bool telling me if I found anything,
//you could skip the bool and just use else in the foreach :)
bool contains = false;
foreach ( var check in stringToCheck )
{
if ( lines.Any( l => l.Contains( check ) ) )
{
Console.WriteLine( "Found substring" );
Console.WriteLine( s );
contains = true;
}
}
if ( contains == false )
{
Console.WriteLine("Could not find substring");
Console.ReadLine();
}
答案 3 :(得分:0)
试试这个想法:
1.2345789
然后将if (line.Any(x=>CheckKeyWordsInLine(line, stringToCheck)){
//The line contains one of the keywords
}else{
//The line does not contain any of the keywords
}
函数定义为:
CheckKeyWordsInLine