列表C#查找匹配用户

时间:2013-12-08 00:45:48

标签: c# asp.net

我在ASP.NET上有这个List,我想找到从textbox给出的connectionid,找到匹配的用户,并将他的缺口写入另一个文本框。我怎样才能做到这一点?

    static List<User> users = new List<User>();
    class User
    {
       public string connectionid { get; set; }
       public string nick { get; set; }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        //I want to find connectionid from TextBox1, write the matching User nick into TextBox2
    }

4 个答案:

答案 0 :(得分:3)

也许这会有所帮助。

foreach(User _user in users)
{
   if(_user.connectionid == TextBox1.Text)
   {
      TextBox2.Text = _user.nick;
      break;
   }
}

更新

在找到匹配项时将break语句添加到exit循环。

答案 1 :(得分:1)

这应该有效:

        string connectionid = GetConnectionid();
        try
        {
            User user = users.Find(u => u.connectionid == connectionid);
        }
        catch (Exception)
        {
             // not found
        }

答案 2 :(得分:1)

试试这个

protected void Button2_Click(object sender, EventArgs e)
{
  try
  {
     //I want to find connectionid from TextBox1, write the matching User nick into TextBox2
     string tempid = TextBox1.Text.Trim();
     List <User> data = (from user in users 
                              where user.connectionid == tempid  
                         select user).ToList();

    foreach(User aUser in data)
    {
      TextBox2.Text = aUser .nick;
    }
  }
  catch(Exception ex)
  {
    //Handle exception
  }

答案 3 :(得分:0)

您可以使用LINQ查找带有User的第一个connectionid

User thisUser = (from user in users
    where user.connectionid == TextBox1.Text.Trim() 
    select user).FirstOrDefault();
if(thisUser != null)
{
   // user was found
   otherBox1.Text = thisUser.nick;
}