【问题标题】:How to search list of values in DataTable?如何在 DataTable 中搜索值列表?
【发布时间】:2021-10-11 04:22:00
【问题描述】:

我有一个包含 n 列数和字符串数组的 DataTable,要在该表中搜索。 我想在 DataTable 中搜索所有这些字符串并将匹配的字符串存储在列表中。

DataTable 中的列是动态的,因此使用下面的代码,我得到了 DataTable 中的列列表。

但不确定如何使用 LINQ 或任何其他具有最佳可行方法的技术搜索和获取匹配记录。

DataColumn[] cols = dt.Columns.Cast<DataColumn>().ToArray();

【问题讨论】:

  • “不影响应用程序的性能”一切都会影响性能,尤其是当您在巨大的 DataTable 字符串中搜索时
  • 您想搜索字符串,如果找到它们,请将它们存储在列表中。所以你有一组搜索字符串,而想要的结果是一个子集,它只包含找到的那些字符串?
  • @TimSchmelter - 是的,你是对的.. 我的意思是没有太大影响.. 最好的方法..
  • @TimSchmelter - 是的,这就是预期。我想将匹配的结果集存储在列表中。

标签: c# asp.net .net datatable


【解决方案1】:

这应该可行:

DataColumn[] cols = dt.Columns.Cast<DataColumn>().ToArray();
var rows = dt.AsEnumerable();
List<string> foundList = searchList
    .Where(s => rows.Any(r => cols.Any(c => r[c].ToString().Equals(s))))
    .ToList();

但这会更有效率:

HashSet<string> searchStrings = new HashSet<string>(searchList); // or use a HashSet<string> instead of a list in the first place
List<string> foundList = new List<string>();
foreach (DataRow row in dt.Rows)
{
    IEnumerable<string> matches = cols
       .Select(c => row[c].ToString())
       .Where(searchStrings.Contains); // Contains is O(1) operation
    foreach (string match in matches)
    {
        foundList.Add(match);
        searchStrings.Remove(match);   // Remove is O(1) operation. It has another advantage: at the end searchStrings contains only strings that were not found
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    • 2017-03-27
    • 1970-01-01
    相关资源
    最近更新 更多