dmr
dmr

Reputation: 19

vb.net/Linq: how can I use a Linq using Generic classes?

I have the next structure:

public class mysample

    public property status as integer

end class

Dim mylist=new List(Of mysample)

Dim item as new mysample
item.status=1
mylist.add(item)

Dim item1 as new mysample
item2.status=1
mylist.add(item1)
...

I have next function which it is calculating something:

Function test(Of T)(newstatus as integer, mylist as List(of T)) as integer

    Dim res as integer = myList.Where(Function(x) x.status=newstatus).First.status

    Return res

End function

The call is where I am interested to execute: test(Of mysample)(2, mylist)

I have mysample in different projects and they can not be in the same for this reason I decided to use generic list to do my Linq calcultion.

THE PROBLEM IS IN FUNCTION WHICH TELL ME STATUS IS NOT MEMBER OF T OBJECT.

How can I solve this issue? all clases has status but I have different classes and I pass the name as generic type.

Upvotes: 0

Views: 186

Answers (2)

D Stanley
D Stanley

Reputation: 152566

STATUS IS NOT MEMBER OF T OBJECT.

Yes, because you have not constraint T in any way. It would be perfectly legal to call

test(Of Integer)(2, new list(of Integer))

which would fail because Integer does not have a status property. You either need to constrain T to be of some type that has a status property (either a base class or a common interface), or don't make it generic:

Function test(newstatus as integer, mylist as List(of mystatus)) as integer

    Dim res as integer = myList.Where(Function(x) x.status=newstatus).First.status

    Return res

End function

I have mysample in different projects

You mean you have several classes names mystatus in several projects? Then they are not the same class.

all classes has status but I have different classes and I pass the name as generic type

The create at least an interface that has a Status property and use that to constrain the generic parameter in Test.

Upvotes: 1

Bradley Uffner
Bradley Uffner

Reputation: 16991

Do the classes share a common base class or interface? If so you should place a filter on the generic type like this:

Function test(Of T as CommonBaseClassOrInterface)(newstatus as integer, mylist as List(of T)) as integer

That will allow you to access any members on CommonBaseClassOrInterface. If they currently don't share a base class or interface you should consider adding one, making sure that Status is a member.

If you can't give them a base class or interface for some reason, you can still do this using reflection, but I DO NOT recommend going that direction.

Upvotes: 4

Related Questions