我有一个包含学生详细信息(名字、姓氏、性别、学位和刻录日期)的 datagridview
我编写这段代码来执行“键盘搜索”(对于这个例子,我在本地“加载”数据):
public class StudentDetails
{
public string firstName;
public string lastName;
public string gender;
public string degree;
public DateTime burnDate;
};
public List<StudentDetails> studentSearchList = new List<StudentDetails>(); // Contain all dgv for searches
private void Form1_Load(object sender, EventArgs e)
{
refreshDataGridView();
}
private void refreshDataGridView()
{
for (int i = 0; i < 1000; i++)
{
StudentDetails sd = new StudentDetails();
sd.firstName = GetRandomFirstName();
sd.lastName = GetRandomLastName();
sd.gender = GetRandomGender();
sd.degree = GetRandomDegree();
sd.burnDate = GetRandomBurnDate();
studentSearchList.Add(sd);
addRowToDataGrid(sd);
}
}
bool detailsContain(StudentDetails sd, string s)
{
if (sd.firstName.ToLower().Contains(s) ||
sd.lastName.ToLower().Contains(s) ||
sd.gender.ToLower().Contains(s) ||
sd.degree.ToLower().Contains(s) ||
sd.burnDate.ToShortDateString().ToString().Contains(s))
return true;
else
return false;
}
void addRowToDataGrid(StudentDetails sd)
{
string[] row = new string[] { sd.firstName, sd.lastName, sd.gender, sd.degree, sd.burnDate.ToShortDateString().ToString() };
dataGridView1.Rows.Add(row);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
List<StudentDetails> list_SD = new List<StudentDetails>();
String s = textBox1.Text;
s = s.ToLower().Trim();
foreach (StudentDetails sd in studentSearchList)
if (detailsContain(sd, s)) list_SD.Add(sd);
// Clear old rows
dataGridView1.Rows.Clear();
dataGridView1.Refresh();
// Adding the new rows
foreach (StudentDetails sd in list_SD)
addRowToDataGrid(sd);
}
我的问题是搜索速度太慢,我不知道如何提高速度。我试图声明另一个包含所有数据库的列表,并仅用最后一个搜索结果填充 studentSearchList,直到用户按下删除字符,但这并没有太大帮助,而且它会消耗内存……</p>
也许有人有好的搜索算法可以建议?
谢谢