如何搜索List <string>?</string>

时间:2014-05-01 19:30:08

标签: c# list

我有表tbl_employee的数据库。在表中我存储用户名。我使用以下代码将所有用户名保存到List中:

string name = txtUsername.Text;       
List<string> lst = new List<string>();

NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=db;User Id=postgres;Password=postgres;"); 

conn.Open();
string sql = "SELECT username FROM tbl_employee";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);  
NpgsqlDataReader dr = command.ExecuteReader();  
while (dr.Read())
{
    lst.Add(dr.GetString(0));
}

现在,我的问题是如何搜索我的列表(lst)以查看列表中是否存在从文本框(名称)输入的用户?

我试过这个:

if (lst.FindString(name)) 
    //Says it has some invalid arguments

而且:

if (lst.Exists(element => element == name)) 
    //It says name exists even though it doesn't

3 个答案:

答案 0 :(得分:3)

您可以使用Contains

if (lst.Contains(name)) ...

但是,如果这是所有您正在使用该列表,我建议您更改此代码,以便直接从数据库查询tbl_empoyee表。我不熟悉NpgsqlCommand,但它应该看起来像这样:

bool result = false;
string sql = "SELECT username FROM tbl_employee WHERE username = :name";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);  
command.Parameters.AddWithValue("name", name);
NpgsqlDataReader dr = command.ExecuteReader();  
while (dr.Read())
{
    result = true; // record found
}

或者像这样(关于 Tim Schmelter &#39; s suggestion):

string sql = "SELECT COUNT(*) FROM tbl_employee WHERE username = :name";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);  
command.Parameters.AddWithValue("name", name);
int found = (int)command.ExecuteScalar();  // 1 = found; 0 = not found

答案 1 :(得分:2)

尝试使用lst.Contains(name)

答案 2 :(得分:1)

谢谢!正如你的建议,我把它改成了数。这是我的最终代码:

string name = txtUsername.Text;       

NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=db;User Id=postgres;Password=postgres;"); 

conn.Open();
string sql = "SELECT COUNT(*) FROM tbl_employee WHERE username = @val1";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);  
command.Parameters.AddWithValue("@val1", name);
var result = command.ExecuteScalar();
int i = Convert.ToInt32(result);
if (i != 0)
{
    FormsAuthentication.RedirectFromLoginPage(name, Persist.Checked);
}
else
{
    lblMessage.Text = "Invalid username or password";
 }