LINQ query for an object with an unknown class

I have an array of objects of class unknown (to the current method). I know that every class has a "Number" property. I am trying to write a LINQ query where I am looking for an object with the next number in the sequence. AKA, I'm in number 8, using the LINQ query to find the object where Number = 9.

Has anyone received an offer?

In addition, I often use reflection, so don't worry about it.

+4
source share
5 answers

If, as you pointed out elsewhere, you have developed all the classes, then you can put this number property in the interface and all classes implement this interface. Then in the linq query use the interface.

+1
source

You can create an interface - INumber with the property number. Each of the objects that you have in the array can implement this interface.

Thus, you will have an array of the known type INumber. Thus, your request will be easy to debug and maintain.

+3
source

If all objects inherit from a known interface, you can direct them, for example.

var next = items.Cast<IHasNumber>.FirstOrDefault(x => x.Number == index + 1); 

If it is not, you can use dynamic , for example.

 var next = items.Cast<dynamic>.FirstOrDefault(x => x.Number == index + 1); 

If you have control over the types, then I would have them implement the interface so that you can use the first method, which should be much faster than the second. In this case, your collection will probably be an IEnumerable<IHasNumber> for starters, and you donโ€™t even have to drop it.

+3
source

If you really donโ€™t have a general type that can be reduced for some reason and for some reason cannot enter such a type, then you can use a dynamic keyword. I don't have access to the compiler at the moment, but can your method accept a collection of dynamic objects and request them?

For instance:

 IEnumerable<dynamic> collection = ...; var numbers = from x in collection select x.Number; 
+1
source

To avoid performance issues, you can use the following method:

 static void Main(string[] args) { object[] objs = GetInitialData(); var accessor = GetGetterHelper<int>(objs[0].GetType(), "Number"); var res = from a in objs where accessor(a) == 7 select a; } static Func<object, T> GetGetterHelper<T>(Type type, string methodName) { var methodInfo = type.GetProperty(methodName).GetGetMethod(); return x => (T)methodInfo.Invoke(x, new object[] {}); } 
+1
source

All Articles