为什么我不能查询Microsoft.Office.Interop.Excel.Connections?

时间:2016-01-07 21:15:38

标签: c# excel linq lambda interop

Connections对象是IEnumerable per:

https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.connections.aspx

我只想在foreach

中删除带有lambda表达式的注释行

这样:

    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]);
    }

2 个答案:

答案 0 :(得分:1)

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]);
}

答案 1 :(得分:1)

  

为什么我无法查询Microsoft.Office.Interop.Excel.Connections?

您误解了Enumerable.Cast<TResult>泛型类型参数。

根据文件:

  

语法:

     

public static IEnumerable&lt; TResult&gt; Cast&lt; TResult&gt;(这个IEnumerable来源)

     

返回值:

     

IEnumerable&lt; T&gt;包含源序列强制转换的每个元素指定类型

很快,TResult是集合元素的类型,而不是您尝试使用它时集合的类型。

.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]);
}

P.S。我想知道是什么阻止了你首先解决这个问题。

当我从VS

中提取样本中的代码时
Workbook book = null;
foreach (WorkbookConnection connection in book.Connections.Cast<Connections>().Where(c => c.Type == XlConnectionType.xlConnectionTypeOLEDB))
{
}

我收到指向c.Type

的编译错误
  

错误CS1061:&#39;连接&#39;不包含&#39; Type&#39;的定义没有扩展方法&#39; Type&#39;接受第一个类型为&#39; Connections&#39;可以找到(你错过了使用指令或程序集引用吗?)

清楚地表明c不是您所期望的,并且确实用鼠标将其悬停显示c的类型为Connections