如何在 DataTable 中搜索值列表?

How to search list of values in DataTable?

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

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

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

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

这应该有效:

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
    }
}