Ilaria
Ilaria

Reputation: 187

Anonymous Type Error using Union

I am trying to use Union and my variable type is decimal. I am getting the following exception:

Instance argument:cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.ParalelQuery<AnonymousType#2>'


And the code:

queryResults = (from lI in Entities.LI
               select new { lI, lI.abc })
               .Union(from lI in Entities.LI
                             from R in Entities.RL
                             where lI.oid == R.lIOid 
                             select new { lI, R.Quantity });

Upvotes: 3

Views: 910

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

You can Union two anonymous types as long as their types are the same. This includes field names. In your case, the first type is {lI, abc} and the second one is {lI, Quantity}, so merging them wouldn't work. You need to decide on a single name, - Quantity, abc, or something completely different.

Giving both fields identical names will fix the problem, assuming that their types are already the same:

queryResults = (from lI in Entities.LI
           select new { lI, Quantity = lI.abc }) // <<== Added "Quantity ="
           .Union(from lI in Entities.LI
                         from R in Entities.RL
                         where lI.oid == R.lIOid 
                         select new { lI, R.Quantity });

Upvotes: 3

ChrisF
ChrisF

Reputation: 137148

The error message is telling you exactly what the problem is. You can't convert one anonymous type to another.

You have this as your first select statement:

select new { lI, lI.abc }

and this as your second:

select new { lI, R.Quantity }

These are producing two different objects, the first has whatever lI is plus a string. The second has 'lI` and a numeric value.

Try this:

select new { lI, lI.abc, 0 }

and:

select new { lI, "", R.Quantity }

Upvotes: 5

Related Questions