环顾四周,无法弄清楚如何做到这一点。
我试图查询数据表。我在第一列搜索字符串值,我需要在第二列中返回与其对应的整数。
当我有这个整数时,我需要将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);
}
我似乎无法在任何地方找到这个,所以任何帮助都会受到赞赏
答案 0 :(得分: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#中使用==喜欢