Skip to content

SelectMany not work over JSON #858

@changeforan

Description

@changeforan

1. Description

I want to use SelectMany over an object which is deserialized from a JSON but get this error:

Exception has occurred: CLR/System.ArgumentException
An unhandled exception of type 'System.ArgumentException' occurred in System.Linq.Expressions.dll: 'Expression of type 'System.Object' cannot be used for return type 'System.Collections.Generic.IEnumerable`1[System.Object]''

here is my code snip

using System.Linq.Dynamic.Core;
using Newtonsoft.Json;
var json = """
    [{
        "PhoneNumbers": [
            { "Number": "123" },
            { "Number": "456" }
        ]
    },
    {
        "PhoneNumbers": [
            { "Number": "789" },
            { "Number": "012" }
        ]
    }]
""";
var people = JsonConvert.DeserializeObject(json) as IEnumerable<dynamic> ?? [];
var numbsers = people.AsQueryable().SelectMany("PhoneNumbers").ToDynamicList();
Console.WriteLine(JsonConvert.SerializeObject(numbsers));

2. Exception

Exception message:
Exception has occurred: CLR/System.ArgumentException
An unhandled exception of type 'System.ArgumentException' occurred in System.Linq.Expressions.dll: 'Expression of type 'System.Object' cannot be used for return type 'System.Collections.Generic.IEnumerable`1[System.Object]''
Stack trace:
at System.Linq.Expressions.Expression.ValidateLambdaArgs(Type delegateType, Expression& body, ReadOnlyCollection`1 parameters, String paramName)
   at System.Linq.Expressions.Expression.Lambda(Type delegateType, Expression body, String name, Boolean tailCall, IEnumerable`1 parameters)
   at System.Linq.Expressions.Expression.Lambda(Type delegateType, Expression body, IEnumerable`1 parameters)
   at System.Linq.Dynamic.Core.DynamicQueryableExtensions.SelectManyInternal(IQueryable source, ParsingConfig config, Type resultType, String selector, Object[] args)
   at System.Linq.Dynamic.Core.DynamicQueryableExtensions.SelectMany(IQueryable source, ParsingConfig config, String selector, Object[] args)
   at System.Linq.Dynamic.Core.DynamicQueryableExtensions.SelectMany(IQueryable source, String selector, Object[] args)
   at Program.<Main>$(String[] args)

3. Fiddle or Project

Fiddle

4. Any further technical details

I found a temporary workaround is combining Select and LINQ like this:

public static IQueryable MySelectMany(this IQueryable source, string selector)
{
    return source.Select(selector).ToDynamicList()
        .Select(it => it as IEnumerable<object>)
        .SelectMany(it => it)
        .AsQueryable();
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions