C# 基于查询结果编辑数据表
环顾四周,不知道怎么做 我正在尝试查询数据表。我在第一列中搜索字符串值,需要在第二列中返回与其对应的整数 当我有那个整数时,我需要在整数值上加1,并用更新的信息编辑行C# 基于查询结果编辑数据表,c#,datatable,C#,Datatable,环顾四周,不知道怎么做 我正在尝试查询数据表。我在第一列中搜索字符串值,需要在第二列中返回与其对应的整数 当我有那个整数时,我需要在整数值上加1,并用更新的信息编辑行 public static string hashtag_counter(string message) { int hashcounter = 0; DataTable hashtags = new DataTable(); DataRow row = new DataR
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);
}
我似乎在任何地方都找不到这一点,因此,如果我遵循您问题中的要求,那么您的代码应该是这样的,我们将不胜感激
.....
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#中那样使用==这是单词中的循环。基本上,我正在检查tweet中的Hashtags,因此
if(word.StartsWith(“#”)在原始tweet中查找hashtag。如果word
不在数据表中,并且以hashtag开头,则会将其添加到数据表中。如果它已经在datatable中,我只需要在计数中添加一个。希望这能让你明白,所以你需要忽略每一个不以
开头的单词。快速修复是继续循环的测试。使用IEnumerable Where条件可能会更好地过滤掉foreach循环中直接忽略的单词