2014-11-23 19 views
0

環顧四周,無法弄清楚如何做到這一點。根據查詢結果編輯數據表

我想查詢一個數據表。我搜索字符串值的第一列,我需要返回第二列中對應於它的整數。

當我有這個整數,我需要加1到整數值和編輯與更新信息的行。

public static string hashtag_counter(string message) 
    { 
     int hashcounter = 0; 
     DataTable hashtags = new DataTable(); 
     DataRow row = new DataRow(); 
     hashtags.Columns.Add("Hashtag", typeof(string)); 
     hashtags.Columns.Add("Count", typeof(int)); 


     string[] words = message.Split(' '); 
     foreach (string word in words) 
     { 
      if (word.StartsWith("#")) 
      { 
       if (hashtags.Columns.Contains(word)) 
       { 
        DataRow[] selection = hashtags.Select("Hashtag == " + word); 

       } 
      } 
      else 
      { 
       row = hashtags.NewRow(); 
       row["Hashtag"] = word; 
       row["Count"] = "1"; 
       hashtags.Rows.Add(row); 
      } 

我似乎無法找到這個任何地方,所以任何幫助,將不勝感激

回答

1

如果我按照要求,在你的問題,那麼你的代碼應該是這樣的。

..... 
string[] words = message.Split(' '); 

// Execute the loop ONLY for the required words (the ones that starts with #) 
foreach (string word in words.Where(x => x.StartsWith("#"))) 
{ 
    // Search if the table contains a row with the current word in the Hashtag column 
    DataRow[] selection = hashtags.Select("Hashtag = '" + word + "'"); 
    if(selection.Length > 0) 
    { 
     // We have a row with that term. Increment the counter 
     // Notice that selection is an array of DataRows (albeit with just one element) 
     // so we need to select the first row [0], second column [1] for the value to update 
     int count = Convert.ToInt32(selection[0][1]) + 1; 
     selection[0][1] = count; 
    } 
    else 
    { 
     row = hashtags.NewRow(); 
     row["Hashtag"] = word; 
     row["Count"] = "1"; 
     hashtags.Rows.Add(row); 
    } 

} 

請注意,如果你想在一個字符串字段中選擇,然後你需要周圍使用搜索項報價,你不需要在C#中使用==像

+0

這是在循環話。基本上,我在tweet中檢查Hashtags,所以'if(word.StartsWith(「#」))'在原始推文中尋找hashtag。如果'word'不在數據表中,並以hashtag開頭,則將其添加到數據表中。如果它已經在數據表中,我只需要在計數中加1。希望這個澄清 – 2014-11-23 23:49:56

+0

所以你需要忽略每個不以'#'開頭的單詞。快速修復是繼續循環的測試。可能用IEnumerable Where條件來過濾掉在foreach循環中直接忽略的單詞會更好 – Steve 2014-11-24 00:02:46

相關問題