Passkey after grouping with dynamic linq

Using System.Dynamic.Linq I have a group statement that looks like this:

var rowGrouped = data.GroupBy(rGroup, string.Format("new({0})", c)); 

Where c is just a string array of field names that I need to select in my group. GroupBy in this case returns a IEnumerable (note: not a IEnumerable<T> , because we do not know what T ). A regular GroupBy would return System.Collections.Generic.IEnumerable<IGrouping<TKey, TElement>>

Now I ask the question, how can I iterate over groups so that I have access to the key ( Key is defined in IGrouping<TKey, TElement> , but I do not know TKey and TElement priori)?

I originally tried this:

 foreach (var row in rowGrouped) 

Iterate, but I cannot access row.Key ( row in this case is an object type)

So, I did this:

 foreach (IGrouping<object,dynamic> row in rowGrouped) 

Which, surprisingly, worked ... while the key was a string. If, however, the key is numeric (for example, short ), then I get this error:

 Unable to cast object of type 'Grouping`2[System.Int16,DynamicClass2]' to type 'System.Linq.IGrouping`2[System.Object,System.Object]'. 

I need to iterate through rowGrouped and get the Key for each row , and then iterate over the collection in each group.

+5
source share
1 answer

The problem is that your key is short and you are trying to pass it to the interface where the key is object . Although IGrouping<> has parameters of a covariant type, it simply won’t work, because variance applies only to reference types . Since short is a value type, it will not work.

If you know that the key will always be short , you should use it as such.

 foreach (IGrouping<short, dynamic> row in rowGrouped) ... 

Otherwise, if it is possible that it could be a value type or a reference type, it is easiest to save the entire string as dynamic .

 foreach (dynamic row in rowGrouped) ... 

Although I personally had problems with this. It may be a mistake, but the runtime cannot understand that in this case the property has the Key property. I can’t tell you why, but remember that.

+2
source

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


All Articles