Home > other >  Linq Select throwing exception when accessing to fields of COM objects
Linq Select throwing exception when accessing to fields of COM objects

Time:08-09

I have below a list of Outlook.Recipient objects:

List<Outlook.Recipient> myList

The Outlook.Recipient object has a field named Name and I am trying to create a comma separated string list as below:

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

The outcome should be (Name field contains email addresses as string):

[email protected]; [email protected]

This throws below exception:

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.`

CodePudding user response:

LINQ cannot support the COM object method invocation as part of its projection in ToArray().

As a result, you can manually loop to create an array yourself without LINQ:

var names = new string[myList.Count];
    
for (int i = 0; i < names.Length; i  )
{
    names[i] = myList[i].Name;
}
    
string.Join(";", names);

That said, if you are going through the trouble of manually looping, you can avoid the new array and string.Join calls and use a string builder to build the result yourself:

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();

CodePudding user response:

The exception states the reason why you can't dot that:

Evaluation of methods on COM objects is not supported in this context.

Use the for loop instead where you could build the result string.

  • Related