开发者

Using LINQ to find keyword in all properties in object graph

I have a survey that's stored in a large object graph of variable depth, depending on how many sections and sub-sections the user chooses to create. I need to be able to sear开发者_如何转开发ch through all the properties for each object in the object graph and see if that property's .ToString() contains a certain keyword that's being searched for.

Can I use LINQ to accomplish this, or do I have to use reflection and loops? The goal is to be able to say something like "Find me all objects in this object graph where one (or more) of its properties contains the substring test".


LINQ is not the right tool for this - this should be impossible with the build-in query operations without heavy usage of reflection in the queries.

You can of course traverse the object graph using reflection but this is not going to be a fast solution and you may have to account for some nasty things like cycles in the object graph.

If the classes constituting the object graph are under your control I strongly suggest to build this functionality into the classes. You could for example create an interface and implement on all classes. Then you can recursively analyze the object graph without relying on reflection.


If I understand correctly, you are trying to use LINQ to flatten out a tree structure. For this I used Generate from MoreLinq. But I had to create my own Generate in the case an object can have more than 1 child. Reply in the comments if you'd like to see my implementation and sample code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜