2014-11-23 88 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