OK OK, I know this is a hack, but this was for a tiny data-manipulation project and I wanted to play around. 😉
I was always under the impression that the compiler would examine all anonymous types used in a C# program and if the properties were the same, it would only create one class behind the scenes.
So let’s say I want to create an anonymous type out of some typed datasets that I have:
var smallData1 = new smallData1().GetData().Select(
x => new { Name = x.NAME, x.ADDRESS, City = x.CITY, State = x.STATE,
Zip = x.ZIP, Country = x.COUNTRY, ManagerName = x.MANAGER_NAME,
ManagerID = x.MANAGER_ID });
var smallData2 = new smallData2().GetData().Select(
x => new { x.Name, x.ADDRESS, x.City, x.State, x.Zip, x.Country,
x.ManagerName,x.ManagerID });
I can now do fun things like smallData2.Except(smallData1); etc., and it all works.
Now, what if I have a bigger pair of anonymous types:
var bigData1 = new BigAdapter1().GetData().Select(
x => new { x.FirstName, x.LastName, x.Address, x.City, x.State,
x.Zip, x.Country, x.Phone, x.Email, x.Website, x.Custom1, x.Custom2,
x.Custom3, x.Custom4, x.Custom5, x.Custom6, x.Custom7, x.Custom8, x.Custom9,
x.Custom10, x.Custom11, x.Custom12, x.Custom13, x.Custom14, x.Custom15,
x.Custom16, x.Custom17, x.Custom18, x.Custom19, x.Custom20, x.Custom21,
x.Custom22, x.Custom23, x.Custom24, x.Custom25, x.Custom26, x.Custom27,
x.Custom28, x.Custom29});
var bigData2 = new BigAdapter2().GetData().Select(
x => new { x.FirstName, x.LastName, x.Address, x.City, x.State, x.Zip,
x.Country, x.Phone, x.Email, x.Website, x.Custom1, x.Custom2, x.Custom3,
x.Custom4, x.Custom5, x.Custom6, x.Custom7, x.Custom8, x.Custom9, x.Custom10,
x.Custom11, x.Custom12, x.Custom13, x.Custom14, x.Custom15, x.Custom16,
x.Custom17, x.Custom18, x.Custom19, x.Custom20, x.Custom21, x.Custom22,
x.Custom23, x.Custom24, x.Custom25, x.Custom26, x.Custom27,
x.Custom28, x.Custom29});
Now when I do bigData2.Except(bigData1); the compiler complains:
Instance argument: cannot convert from
'System.Data.EnumerableRowCollection<AnonymousType#1>' to
'System.Linq.IQueryable<AnonymousType#2>'
Why? Too many properties, so the compiler decides it’s not worth it to optimize?
Thanks!
Yep. Its not the number of properties. How sure are you that your adapters are returning exactly the same data types?