Tengo un DataTable con un número n de columnas y una matriz de cadenas para buscar en esta tabla. Quiero buscar todas estas cadenas en DataTable y almacenar cadenas coincidentes en la lista.
Las columnas en DataTable son dinámicas, por lo que al usar el siguiente código obtuve una lista de columnas de DataTable.
Pero no estoy seguro de cómo buscar y obtener registros coincidentes utilizando LINQ o cualquier otra técnica con el mejor enfoque posible.
DataColumn[] cols = dt.Columns.Cast<DataColumn>().ToArray();Esto debería funcionar:
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();Pero esto sería más eficiente:
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 } }