如何修改C#方法从动态表格中获取首行数据
没问题,我帮你调整这个方法,让它每次调用只返回表格的首行数据。核心思路就是跳过遍历所有行的逻辑,直接定位到第一行(tableRow[0])来处理,同时加个简单的判断避免空表导致的索引越界问题。
修改后的代码
public static Dictionary<string, IWebElement> GetlatestResults(String GridPath, String GridPathHeader) { var Result = new Dictionary<string, IWebElement>(); var workflowtable = DriverContext.Driver.FindElement(By.XPath(GridPath)); IList<IWebElement> tableRow = workflowtable.FindElements(By.TagName("tr")); var workflowTableHeader = DriverContext.Driver.FindElement(By.XPath(GridPathHeader)); IList<IWebElement> colElements = workflowTableHeader.FindElements(By.TagName("th")); // 仅处理首行数据,添加空判断避免索引越界 if (tableRow.Count > 0) { var firstRow = tableRow[0]; int headerValueIndex = 0; IList<IWebElement> rowValues = firstRow.FindElements(By.TagName("td")); foreach (var rowValue in rowValues) { Result.Add(colElements[headerValueIndex].Text, rowValue); headerValueIndex++; } } return Result; }
关键修改点说明
- 移除了遍历所有表格行的
foreach循环,直接通过tableRow[0]获取首行元素 - 新增
if (tableRow.Count > 0)判断,防止表格为空时出现IndexOutOfRangeException,提升方法健壮性 - 保留了原有的表头与单元格的映射逻辑,确保返回的字典依然以表头文本为键、对应单元格元素为值
内容的提问来源于stack exchange,提问作者user8075070
相关产品推荐
相关产品推荐

