PilgrimViis PilgrimViis - 2 months ago 9
C# Question

How to properly union different IQueryables and then serialize them in JSON

I've 2 different data sources. Let's say, for example, that one source contains ids and lastnames and second source contains other ids and lastnames. I want to combine them in JSON like this:

{
"Full": [
{
"id": 1,
"lastname": "Doe"
},
{
"id": 5,
"lastname": "Smith"
}
]
}


To achieve it I'm trying "Union" Ids from different sources, then
"Union" lastnames from different sources and after that, "Zip" it in one anonymous typed variable called "full".

var ids = idsFromOneSource.Union(idsFromOtherSource);
var lastNames = lastNamesFromOneSource.Union(lastNamesFromOtherSource);

var full = new
{
Full = ids.Zip(lastNames, (i, l) => new { id = i, lastName = l })
};
return JsonConvert.Serialise(full);


Where idsFromOneSource, idsFromOtherSource are
IQueryable<int>
and lastNamesFromOneSource, lastNamesFromOtherSource are
IQueryable<string>


I'm getting this error.


LINQ to Entities does not recognize the method 'System.Linq.IQueryable
1[<>f__AnonymousType2
2[System.Int32,System.String]] Zip[Int32,String,<>f__AnonymousType2
2](System.Linq.IQueryable
1[System.Int32], System.Collections.Generic.IEnumerable
1[System.String], System.Linq.Expressions.Expression
1[System.Func
3[System.Int32,System.String,<>f__AnonymousType2
2[System.Int32,System.String]]])' method, and this method cannot be translated into a store expression.


For serialization I'm using NewtonSoft Json.net, but looks like the problem not in it. I will be grateful for any help.

Answer

You can't Zip within linq-to-Entities. You could convert them to linq-to-objects calls by calling AsEnumerable:

    var ids = idsFromOneSource.Union(idsFromOtherSource);
    var lastNames = lastNamesFromOneSource.Union(lastNamesFromOtherSource);

    var full = new
    {
        Full = ids.AsEnumerable().Zip(lastNames, (i, l) => new { id = i, lastName = l })
    };
    return JsonConvert.Serialise(full);

but one caveat that you may be aware of is that the collections need to be aligned exactly (in the same order). It seems like it would be safer to have some key to join the different sets together.

Comments