如何使用LINQ在object[,]二维数组中查找指定值
解决二维矩形数组(object[,])查找特定行的问题
你遇到的CS1503错误原因很直接:Array.Find<T>是专门针对一维数组设计的API,而object[,]属于二维矩形数组,两者类型不兼容,所以无法直接传入。下面提供几种比手动循环更优雅的实现方式:
1. 直接用LINQ查询所有匹配行
通过Enumerable.Range生成行索引,将二维数组的每一行转换为一维数组后再筛选:
object[,] mx = new object[,] { { "ABC", 123 }, { "DEF", 456 }, { "ABC", 789 } }; string targetValue = "ABC"; // 获取所有第一列等于目标值的行 var matchedRows = Enumerable.Range(0, mx.GetLength(0)) .Select(rowIdx => Enumerable.Range(0, mx.GetLength(1)) .Select(colIdx => mx[rowIdx, colIdx]) .ToArray()) .Where(row => row[0] is string cell && cell.Equals(targetValue)) .ToList();
这里用row[0] is string cell做类型检查,避免强制转换时可能出现的InvalidCastException。
2. 查找第一个匹配的行(类似Array.Find的效果)
如果只需要第一个符合条件的行,用FirstOrDefault替代Where:
var firstMatchedRow = Enumerable.Range(0, mx.GetLength(0)) .Select(rowIdx => Enumerable.Range(0, mx.GetLength(1)) .Select(colIdx => mx[rowIdx, colIdx]) .ToArray()) .FirstOrDefault(row => row[0] is string cell && cell.Equals(targetValue));
3. 封装扩展方法复用逻辑
如果需要多次处理二维数组的行查询,可以写一个扩展方法将二维数组转换为行的枚举:
public static class ArrayExtensions { public static IEnumerable<object[]> GetRows(this object[,] matrix) { int rowCount = matrix.GetLength(0); int colCount = matrix.GetLength(1); for (int row = 0; row < rowCount; row++) { object[] currentRow = new object[colCount]; for (int col = 0; col < colCount; col++) { currentRow[col] = matrix[row, col]; } yield return currentRow; } } }
之后使用就会非常简洁:
// 获取所有匹配行 var matchedRows = mx.GetRows().Where(row => row[0] is string cell && cell == targetValue).ToList(); // 获取第一个匹配行 var firstMatch = mx.GetRows().FirstOrDefault(row => row[0] is string cell && cell == targetValue);
内容的提问来源于stack exchange,提问作者Kevin S. Miller
相关产品推荐
相关产品推荐

