How do I use a .NET method with argument type IEnumerabl​e<System.S​ingle>?

9 views (last 30 days)
I want to pass my MATLAB data to a .NET method that has an argument type System.Collections.Generic.IEnumerable<System.Single>.  
How can I pass my data as System.Collections.Generic.IEnumerable<System.Single>? 

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 16 May 2025
Edited: MathWorks Support Team on 16 May 2025
IEnumerable<T> is an interface for the .NET System.Collections.Generic namespace that supports iteration over a collection of objects (for example, a List) of the type T. In this case, the type T is System.Single.  
The example below illustrates how to pass MATLAB data as type System.Collections.Generic.IEnumerable<System.Single> to a .NET method, using the Sum method of the System.Linq.Enumerable static .NET Base class as an example. 

Determine what assembly to load 

When using .NET Base classes, such as System.Linq.Enumerable, you may need to load an assembly, but the assembly to load may depend on what version of .NET you are using:  Framework or Core. See Steps to determine the required assembly to determine which assembly to load.

Load the assembly 

Run the following code in MATLAB to load the assembly and view the signature for the System.Linq.Enumerable.Sum method. 
% Load the required assembly % .NET Core and Framework require different assemblies for System.Linq.Enumerable env = dotnetenv; if (env.Runtime == "framework") NET.addAssembly('System.Core'); else % Required assembly for .NET Core 8, for example NET.addAssembly('System.Linq'); end % Show methods for the Enumerable class methods('System.Linq.Enumerable','-full');
In the example code, you can see that .NET Framework requires the System.Core assembly, and .NET Core 8 requires the System.Linq assembly.  
You can use the dotnetenv function in MATLAB to display or set the version of .NET.  

Prepare the data  

Create the MATLAB data, copy to the required .NET type, and display the data. 
% Create the MATLAB data. MATLAB data are type "double", by default. data = [1.8, 2.3, 3.9, 4.2, 5.6]; % Create a .NET Generic Collections List of type System.Single (float in .NET). % The .NET Generic Collections List implements the IEnumerable interface. dotNetList = NET.createGeneric('System.Collections.Generic.List',{'System.Single'}); % Add the data values to the .NET List for i=1:numel(data) dotNetList.Add(data(i)); end % Display the contents of the .NET List disp('Contents of the .NET List:'); for i = 0:dotNetList.Count - 1 disp(dotNetList.Item(i)); end

Compute and display the sum  

Use the .NET System.Linq.Enumerable.Sum method to compute the sum.  
% Compute and display the sum totalSum = System.Linq.Enumerable.Sum(dotNetList); fprintf('Sum of list values = %f\n', totalSum);

More Answers (0)

Tags

No tags entered yet.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!