我在搜索我的Arraylist
时有问题。数组列表存储了关于许多团队的各种信息,例如其徽标的图像路径和团队名称等。它正在使用StreamReader
我希望用户在Textbox
中输入一些东西,例如团队名称,然后程序将在我的数组列表中搜索所述字符串,并打开另一个表单,其中搜索团队的信息将使用Form.Load
过程加载到屏幕上
简单地说。
private void btn_Search_Click(object sender, EventArgs e)
{
//what code do I write here?
}
我知道我可能在这里对我目前的编码知识有点深入,所以帮助将是感激的。
编辑:不幸的是,它必须在数组列表中,抱歉给您带来不便。
如果可以使用LINQ:
string nameToMatch = "Tigers"; //can you tell who's from Michigan?
List<Team> teams = new ArrayList<Team>();
//fill team data here
Team selected = teams.FirstOrDefault(t => t.TeamName.Equals(nameToMatch, StringComparison.OrdinalIgnoreCase));
这样应该可以工作。(这将完全匹配文本,但允许搜索不区分大小写。你可以在这里阅读其他选项
如果你想匹配所有"部分匹配"的列表,你可以这样做:
List<Team> matchedTeams = teams.Select(t => t.TeamName.Contains(nameToMatch));
阅读这里的扩展重载包含一个StringComparison
枚举值
如果你像我一样不熟悉LINQ,你可以使用foreach循环。像这样:
String nameToMatch = textBox1.text; //read from the text box
foreach (Object obj in Teams)
{
MyTeam team = (MyTeam)obj; //MyTeam is an object you could write that would store team information.
if (team.TeamName.ToUpper() == nameToMatch.ToUpper()) //case insensitive search.
{
FormTeam frmTeam = new FormTeam(team); //windows form that displays team info.
frmTeam.Visible = true;
break; //if team names are unique then stop searching.
}
}
最坏的情况是相当糟糕,但至少对我来说,它比LINQ更容易理解。祝你好运,希望能有所帮助。
你可以使用下面的代码来填充你的数组列表:
// ArrayList class object
ArrayList arrlist = new ArrayList();
// add items to arrlist collection using Add method
arrlist.Add("item 1");
arrlist.Add("item 2");
arrlist.Add("item 3");
arrlist.Add("item 4");
arrlist.Add("item 5");
在数组列表
中搜索string teamName= this.txtTeamName.Text;
// for loop to get items stored at each index of arrlist collection
for (int i = 0; i < arrlist.Count; i++)
{
if(arrlist[i].toString()==teamName)
// open a new form for show the found team details
}
最好将"Team Details"表单的构造函数改为"Team name"
frmTeamDetails(team myteam)
然后在上面的FOR语句中使用以下代码:
frmTeamDetals frm=new frmTeamDetals(teamName);
frm.ShowDialog();