我正在从一个大文本文件中逐行阅读。在这些文件中偶尔有字符串,它们在预设的可能性列表中,我希望检查当前正在读取的行是否与可能性列表中的任何字符串匹配。如果有匹配项,我只想将它们附加到不同的列表,然后继续我用来读取文件的循环。
我只是想知道是否有更有效的方法来执行 line.Contains() 或对列表中的第一个元素进行等价检查,然后是第二个元素,等等而不使用嵌套循环或长 if 语句充满“或”。
我现在拥有的示例:
List<string> possible = new List<string> {"Cat", "Dog"}
using(StreamReader sr = new StreamReader(someFile))
{
string aLine;
while ((aLine = sr.Readline()) != null)
{
if (...)
{
foreach (string element in possible)
{
if line.Contains(element) == true
{
~add to some other list
continue
}
}
~other stuff
}
}
最佳答案
我不知道更高效的运行时方式,但您可以通过使用 LINQ 来消除大量代码:
otherList.AddRange(File.ReadAllLines(somefile).
.Where(line => possible.Any(p => line.Contains(p)));
关于c# - 有没有更好的方法来调用 C# 中对象列表的比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22234495/