列表比较不起作用
本文关键字:不起作用 比较 列表 | 更新日期: 2023-09-27 18:21:17
我正在尝试制作一个应用程序,读取两个文本文件,获取这两个文件,并将它们合并到一个列表中。然后取所述列表,并将其与另一个列表(来自另一个文本文件)进行比较。问题是,无论我做什么,我的程序都会转到else
(见上面写着的行
if (BoysAndGirlsList.Contains(NameEntered) && MostPopularNamesList.Contains(NameEntered))
)。我不知道它为什么会这样。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Linq; //Needed for concat.
namespace Name_Search
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string BoyNames = System.IO.File.ReadAllText(@"D:'Google Drive'Course Work'C# Intro'Student Sample Programs'Chap07'BoyNames.txt"); //Reads BoyNames txt file.
List<string> BoyNamesList = BoyNames.Split(''n').ToList(); //Converts it to a list.
//BoyNamesList.ForEach(Console.WriteLine); <-Testing to make sure that the list is working properly.
string GirlNames = System.IO.File.ReadAllText(@"D:'Google Drive'Course Work'C# Intro'Student Sample Programs'Chap07'GirlNames.txt"); //Reads GirlNames txt file.
List<string> GirlNamesList = GirlNames.Split(''n').ToList(); //Converts it to a list.
List<string> BoysAndGirlsList;
BoysAndGirlsList = BoyNamesList.Concat(GirlNamesList).ToList(); //Adds the lists together.
//BoysAndGirlsList.ForEach(Console.WriteLine); <-Again just testing that the list is working.
string MostPopularNames = System.IO.File.ReadAllText(@"D:'Google Drive'Course Work'C# Intro'Student Sample Programs'Chap07'MostPopularBoyAndGirlNames.txt"); //Reads MostPopularBoyAndGirlNames txt file. Compiled from http://goo.gl/1crLcY.)
List<string> MostPopularNamesList = MostPopularNames.Split(''n').ToList(); //Converts it to a list.
string NameEntered = nameInput.Text;
if (BoysAndGirlsList.Contains(NameEntered) && MostPopularNamesList.Contains(NameEntered))
{
MessageBox.Show("This name is one the most popular names!");
}
else
{
MessageBox.Show("This is not one of the most popular names.");
}
}
}
}
什么东西在这里不能正常工作?我试过放一个休息时间,当我这样做的时候,值对我来说很好。
正如注释所提到的,这个问题可能已经解决了,其中"name"中的多余空格导致它们的比较不相等。当您希望以不区分大小写的方式比较名称时,也会遇到问题。
第一个问题可以通过修剪每个名称中的空白来解决:
BoysAndGirlsList = BoysAndGirlsList.Select(name => name.Trim()).ToList();
MostPopularNamesList = MostPopularNamesList.Select(name => name.Trim()).ToList();
第二个问题可以通过使用不变的事例比较器来解决:
if (BoysAndGirlsList.Contains(NameEntered, StringComparer.InvariantCultureIgnoreCase) &&
MostPopularNamesList.Contains(NameEntered, StringComparer.InvariantCultureIgnoreCase))