Linq Select在访问COM对象的字段时引发异常



下面是Outlook的列表。收件人对象:

List<Outlook.Recipient> myList

Outlook.Repient对象有一个名为Name的字段,我正试图创建一个逗号分隔的字符串列表,如下所示:

string.Join(";", myList.Select(r => r.Name).ToArray());

结果应该是(名称字段包含字符串形式的电子邮件地址(:

hello@gmail.com; hey@hotmail.com

这引发以下异常:

Evaluation of method System.Linq.Enumerable.ToArray(System.Collections.Generic.IEnumerable`1<string>) calls COM method Microsoft.Office.Interop.Outlook.Recipient.get_Name(). Evaluation of methods on COM objects is not supported in this context.`

LINQ不能支持COM对象方法调用作为其在ToArray()中投影的一部分。

因此,您可以在没有LINQ:的情况下手动循环以自己创建阵列

var names = new string[myList.Count];

for (int i = 0; i < names.Length; i++)
{
names[i] = myList[i].Name;
}

string.Join(";", names);

也就是说,如果你正在经历手动循环的麻烦,你可以避免新的数组和string.Join调用,并使用字符串生成器自己构建结果:

var sb = new StringBuilder(myList.Count);
for (int i = 0; i < myList.Count - 1; i++)
{
sb.Append($"{myList[i].Name};");
}

// add the last item in the array without the ;
sb.Append($"{myList[myList.Count - 1].Name}");


var outputNames = sb.ToString();

异常说明了无法点出的原因:

在此上下文中不支持对COM对象上的方法进行求值。

请改用for循环,在那里可以构建结果字符串。

最新更新