I have some Linq to SQL code in C# that I'm trying to access using Matlab 2010b. If my Linq code returns a single item instance, I can access all the properties without problem in Matlab:
dal = Data.PeopleRepository
person = dal.QueryPersonById(1)
person.Name
ans =
John Smith
But if I call a Linq query that returns an IQueryable collection (actually a System.Data.Linq.Table class), I'm struggling to get at the list of Person instances inside!
people = dal.QueryAllPeople()
people =
System.Data.Linq.Table<Data.Person> handle
Package: System.Data.Linq
Properties:
Context: [1x1 Data.PeopleRepository]
IsReadOnly: 0
I've tried converting to an IEnumerable using the GetEnumerator method on people, but I still can't get at the actual Person instances inside. (I'm aware that due to late evaluation the values may not yet actually be retrieved from the database too! Aarggh!) Any pointers appreciated, and apologies if this is unclear - it's my first StackOverflow question...
Had a similar challenge today. It's indeed possible to call extension methods. However, the syntax is a bit clumsy.
In order to enumerate, the IEnumerable.ToArray() extension method is handy. For extension methods, you need to know where they are defined. In this case, the full signature to the method is System.Linq.Enumerable.ToArray<T>(this IEnumerable<T>)
. Matlab won't care about the this
modifier. However, because it's a generic method, you cannot directly use it in Matlab. Instead, the NET.invokeGeneric
Method is needed.
The following example enumerates doubles and converts the result into a Matlab array.
ret = double(NET.invokeGenericMethod('System.Linq.Enumerable', 'ToArray', ...
{'System.Double'}, enumerableInstance));
Since IQueryable<T> : IEnumerable<T>
, the same method (ToArray()
) should do your job. Leave out the conversion to a Matlab double array, and specify the correct element type (Data.Person
, I suppose).
In order to access the static Enumerable class, Matlab needs to load a .NET 3.0 library. Add
NET.addAssembly('System.Core');
for that purpose.
I've only worked Matlab and C# the other way around (calling Matlab from C#) but it looks to me like the problem is that you have an IQueryable instance instead of an IEnumerable in your code.
Try calling people = dal.QueryAllPeople().ToList()
or people = dal.QueryAllPeople.ToArray()
- these will cause a query to be executed - and the data will then hopefully be available inside Matlab.
Update - since extension methods are a no-no... what happens if you try:
myEnumerator = dal.QueryAllPeople().GetEnumerator()
myEnumerator.MoveNext()
firstItem = myEnumerator.Current
firstItem =
myEnumerator.MoveNext()
secondItem = myEnumerator.Current
secondItem =
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With