2013-12-08 84 views
3

我在ASP.NET上有這個列表,我想找到從文本框給出的connectionid,並找到匹配的用戶,並將他的暱稱寫入另一個文本框。我怎樣才能做到這一點?列表C#找到匹配用戶

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 
    } 
+0

查看修改答案 –

回答

3

也許這會有所幫助。

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

UPDATE

新增break語句時,它找到一個匹配退出循環。

0

你可以使用LINQ到找到第一個Userconnectionid

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; 
} 
+0

您不需要數據庫來使用LINQ。它是對集合起作用的C#查詢語言。 – cgTag

1

這應該工作:

 string connectionid = GetConnectionid(); 
     try 
     { 
      User user = users.Find(u => u.connectionid == connectionid); 
     } 
     catch (Exception) 
     { 
      // not found 
     } 
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 
    } 
+0

我有兩個文本框。一個用於輸入,另一個用於顯示 – user3071591

+4

爲什麼所有的冗餘分配? – 2013-12-08 01:06:12