2012-01-13 79 views
0

我正在爲我的IRC中的用戶保留一個計時器。當用戶輸入消息時,我試圖插入消息的用戶名&時間。這是爲了阻止垃圾郵件發送者。滿足條件時將數據追加到數組中?

if(userList.Contains(username)) { 
//check the time of message 
//if last message is 3 seconds ago or greater, continue 
} else { 
//Add username & time into the array keeping all other values too 
} 

問題是我不知道如何將數據追加到數組中。我不知道如何使用新值將其他現有陣列數據複製到新陣列中。這可以做到嗎?

由於array.Contains()不適用於二維數組,因此我可以如何記錄用戶名和時間?我應該在兩個數組中插入數據嗎?

謝謝你的幫助。

+1

陣列通常有一個靜態的大小。爲什麼使用它而不是IEnumerable的其他實現之一(如List)? – 2012-01-13 01:36:09

回答

2

C#中的數組是固定大小的結構。

你想要一個「列表」,這將允許你實現這個先入先出隊列,或者,如果你想刪除並隨機插入一個「字典」。

這兩種結構都將動態分配存儲空間,並允許您擴展和縮減用戶數量。

+0

感謝您的接受。雖然我覺得「Lee Sy En」的答案完整,代碼示例更好! – 2012-01-16 03:20:48

2

您應該創建List<T>Dictionary<K,V>而不是雙暗陣列。首先定義一個具有UserName,TimeOfMessage和Message等字段/屬性的類(例如Message),並創建List<Message>.

2

使用Dictionary<TKey, TValue>

代碼示例,這是粗略的想法,你可以從這裏修改:

private static void Main(string[] args) 
{    
    var list = new Dictionary<string, DateTime>(); 
    list.Add("John", DateTime.Now.AddSeconds(-1)); 
    list.Add("Mark", DateTime.Now.AddSeconds(-5)); 
    list.Add("Andy", DateTime.Now.AddSeconds(-5)); 

    PrintList(ref list); 

    IsSpam(ref list, "John"); 
    PrintList(ref list); 
    IsSpam(ref list, "Andy"); 
    PrintList(ref list); 
    IsSpam(ref list, "Andy"); 
    PrintList(ref list); 
} 

private static void IsSpam(ref Dictionary<string, DateTime> list, string username) 
{ 
    if (list.ContainsKey(username)) 
    { 
     if (list[username] < DateTime.Now.AddSeconds(-3)) 
      Console.WriteLine("Not a spam"); 
     else 
      Console.WriteLine("Spam"); 

     list[username] = DateTime.Now; 
    } 
    else 
    { 
     list.Add(username, DateTime.Now); 
    } 
} 

private static void PrintList(ref Dictionary<string, DateTime> list) 
{ 
    foreach (var c in list) 
     Console.WriteLine("user: {0}, time: {1}", c.Key, c.Value); 
}