Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq with DynamicObject

I have List where MyType : DynamicObject. The reason for MyType inheriting from DynamicObject, is that I need a type that can contain unknown number of properties.

It all works fine until I need to filter List. Is there a way I can do a linq that will do something like this:

return all items where any of the properties is empty string or white space?
like image 583
Goran Avatar asked Oct 07 '22 01:10

Goran


1 Answers

(from the comment) can I do above linq query with List?

Yes, here is how you can do it with ExpandoObject:

var list = new List<ExpandoObject>();
dynamic e1 = new ExpandoObject();
e1.a = null;
e1.b = "";
dynamic e2 = new ExpandoObject();
e2.x = "xxx";
e2.y = 123;
list.Add(e1);
list.Add(e2);
var res = list.Where(
    item => item.Any(p => p.Value == null || (p.Value is string && string.IsNullOrEmpty((string)p.Value)))
);

The ExpandoObject presents an interface that lets you enumerate its property-value pairs as if they were in a dictionary, making the process of checking them a lot simpler.

like image 72
Sergey Kalinichenko Avatar answered Oct 13 '22 09:10

Sergey Kalinichenko