【问题标题】:Check value in datatable with Linq使用 Linq 检查数据表中的值
【发布时间】:2015-12-18 05:30:25
【问题描述】:

我正在创建一个词云,因此我使用正则表达式在 Linq 中拆分我的句子,并对单词进行分组并计算它们的数量。但是,我不希望某些黑名单词出现在我的云中,所以我将这些词放在数据表 (dtBlackList) 中并使用 Linq 进行检查,如下面的代码所示

var result = (Regex.Split(StringsForWordCloud, @"\W+")
                   .GroupBy(s => s, StringComparer.InvariantCultureIgnoreCase)
                   .Where(q => q.Key.Trim() != "")
                   .Where(q => (dtBlackList.Select("blacklistword = '" + q.Key.Trim() + "'").Count() == 0))
                   .OrderByDescending(g => g.Count())
                   .Select(p => new { Word = p.Key, Count = p.Count() })
              ).Take(200);

这个查询会严重影响我的表现吗?这是检查数据表的正确方法吗?

【问题讨论】:

  • 这不是您可以询问这段代码是好是坏的正确区域。最好在此处添加您的帖子Code Review Stack Exchange
  • 什么是StringsForWordCloud?您可以检查 SQL 分析器以查看您的代码运行时生成的查询类型吗?
  • StringsForWordCloud 包含我要为其创建词云的句子。我的后端不是 sql server。

标签: c# asp.net regex linq datatable


【解决方案1】:

一个 LINQ 查询作为这个查询将对使用 Regex.Split 操作找到的每个单词执行一个查询。我指的是这行代码:

.Where(q => (dtBlackList.Select("blacklistword = '" + q.Key.Trim() + "'").Count() == 0))

在我现在工作的项目中,我不得不处理很多性能问题,这些问题都是由类似的情况引起的。

一般来说,执行查询以检查或完成从数据库中提取的数据并不是一个好的做法。

在您的情况下,我认为最好编写一个查询来提取黑名单单词,然后从您刚刚提取的数据集中排除该列表。如下:

var words = Regex.Split(StringsForWordCloud, @"\W+")
    .GroupBy(s => s, StringComparer.InvariantCultureIgnoreCase)
    .Where(q => q.Key.Trim() != "")
    .OrderByDescending(g => g.Count())
    .Select(p => new { Word = p.Key, Count = p.Count() });

// Now extract all the word in the blacklist
IEnumerable<string> blackList = dtBlackList...

// Now exclude them from the set of words all in once
var result = words.Where(w => !blackList.Contains(w.Word)
    .OrderByDescending(g => g.Count())
    .Take(200);

【讨论】:

    猜你喜欢
    • 2021-01-05
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    相关资源
    最近更新 更多