Can I request an ExpandoObject list?

I wonder if it is possible to query ExpandoObject using regular LINQ? The reason is that I have a dynamic ExpandoObject, but I need to do some queries before I can go further.

It has some properties that always remain, for example. Id , Notes , but also some dynamic properties that I cannot control.

Here's what my list of them looks like

 [ { "Id": 1, "FileId": 1, "Notes": "", "1": "12.02.1991" }, { "Id": 2, "FileId": 2, "Notes": "", "1": "12.02.1991" } ] 

The code

As you can see, I have my static elements, and then I make sure that each element of the dynamic keys becomes this property element. In this example, 1 is the key, and 12.02.1991 is the value

 var generatedItems = new List<object>(); foreach (var item in items) { var modifiedItem = new List<KeyValuePair<string, object>> { new KeyValuePair<string, object>("Id", item.Id), new KeyValuePair<string, object>("FileId", item.FileId), new KeyValuePair<string, object>("Notes", item.Notes) }; modifiedItem.AddRange(item.Fields.Select(field => new KeyValuePair<string, object>(field.Key, field.Value))); generatedItems.Add(ConvertToExpandoObjects(modifiedItem)); // Here I construct object from key/value pairs } return generatedItems; // Is it possible to query this thing? 

I don't think this is relevant, but here is my ConvertToExpandoObjects funciton.

 public static dynamic ConvertToExpandoObjects(IEnumerable<KeyValuePair<string, object>> pairs) { IDictionary<string, object> result = new ExpandoObject(); foreach (var pair in pairs) result.Add(pair.Key, pair.Value); return result; } 

I tried to just do something like generatedItems.Where(x => x.); , but obviously I have nothing to work for, because he does not know that these objects have Id , etc.

So is it possible to request it, and if so, how?

+4
source share
1 answer

Your suggestion is correct, you can request a collection of dynamic objects using dot notation.

 var ids = generatedItems.Cast<dynamic>().Select(x => x.Id); 

However, keep in mind that there is no type safety here, and as you said, IntelliSense is useless as you use dynamic objects.

If your code depends on whether one of these objects has an optional property (for example, some have a "Name", others do not), then this will require a little more manual work.

 if((generatedItems as IDictionary<String, object>).ContainsKey("Title")) { } 
+5
source

Source: https://habr.com/ru/post/1501704/


All Articles