为什么我不能查询Microsoft.Office.Interop.Excel.Connections?
Connections对象是一个IEnumerable:
https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.connections.aspx
我只想在foreach中删除带有lambdaexpression式的注释行
这个:
foreach (WorkbookConnection connection in book.Connections) { if (connection.Type != XlConnectionType.xlConnectionTypeOLEDB) continue; var conString = connection.OLEDBConnection.Connection.ToString(); if (conString.Contains("Initial Catalog") && conString.Contains("Data Source")) connection.OLEDBConnection.Connection = conString.Replace(ExlCubeServer, Settings.Default.OLAPServer[1]); }
像这样的东西:
foreach (WorkbookConnection connection in book.Connections.Cast<Connections>().Where(c => c.Type == XlConnectionType.xlConnectionTypeOLEDB)) { //if (connection.Type != XlConnectionType.xlConnectionTypeOLEDB) continue; var conString = connection.OLEDBConnection.Connection.ToString(); if (conString.Contains("Initial Catalog") && conString.Contains("Data Source")) connection.OLEDBConnection.Connection = conString.Replace(ExlCubeServer, Settings.Default.OLAPServer[1]); }
为什么我不能查询Microsoft.Office.Interop.Excel.Connections?
您错误地解释了Enumerable.Cast <TResult>genericstypes参数。
根据文件:
句法:
公共静态IEnumerable <TResult> Cast <TResult>(此IEnumerable源)
返回值:
包含源序列的每个元素的IEnumerable <T>转换为指定的types 。
简而言之, TResult
是收集元素的types,而不是您尝试使用它的收集types。
因此,将.Cast<Connections>()
更改为.Cast<WorkbookConnection>()
将解决此问题:
foreach (var connection in book.Connections.Cast<WorkbookConnection>() .Where(c => c.Type == XlConnectionType.xlConnectionTypeOLEDB)) { var conString = connection.OLEDBConnection.Connection.ToString(); if (conString.Contains("Initial Catalog") && conString.Contains("Data Source")) connection.OLEDBConnection.Connection = conString.Replace(ExlCubeServer, Settings.Default.OLAPServer[1]); }
PS我想知道是什么阻止了你来解决这个问题。
当我从VS中的样本中提取代码时
Workbook book = null; foreach (WorkbookConnection connection in book.Connections.Cast<Connections>().Where(c => c.Type == XlConnectionType.xlConnectionTypeOLEDB)) { }
我得到一个编译器错误指向c.Type
错误CS1061:“连接”不包含“types”的定义,并且没有find接受“连接”types的第一个参数的扩展方法“types”(您是否缺lessusing指令或程序集引用?
这清楚地表明c
不是你所期望的,并且确实用鼠标hover它表明c
是Connections
types的。
book.Connections.ToList().Where(c => c.Type == XlConnectionType.xlConnectionTypeOLEDB).ToList().ForEach(connection => PerformAction(connection)); public static void PerformAction(WorkbookConnection connection) { var conString = connection.OLEDBConnection.Connection.ToString(); if (conString.Contains("Initial Catalog") && conString.Contains("Data Source")) connection.OLEDBConnection.Connection = conString.Replace(ExlCubeServer, Settings.Default.OLAPServer[1]); }