tags:

views:

46

answers:

2

I have two linq queries that I run on two different tables, Car and Truck. From these queries I select the ID, Name, and Company.

var car = from c in db.Cars
          select new {ID = c.ID, Name = c.Name, Company = c.Company};

var truck = from t in db.Trucks
          select new {ID = t.ID, Name = t.Name, Company = t.Company};

How do I append the truck data to the car data using Linq so that the resultant query contains both car and truck data?

+4  A: 

If the resulting types are equivalent, you can use Enumerable.Concat to combine them.

However, I wouldn't normally recommend doing this with anonymous types - instead I'd recommend making a custom class to hold your three (or more) properties. It's possible, given the code above, that the type may be the same post-compilation, but it's impossible to tell for sure without more information.

Personally, I would either use a shared interface (ie: have Car and Truck implement ICompanyInfo with those properties in the interface), and return the car cast into the interface, or make a custom class, and return that from both queries, then use Concat to join them.

Reed Copsey
As long as the anonymous type has the same number of properties, of the same name and type, in the same order, then they are fine to use `Concat` on. The compiler will warn you if the property types don't match.
Enigmativity
@Enigmativity: Yes - hence I said that it would likely work. However, having multiple conditions like that leads to brittle software that's not as nice for long term maintenance. I would not recommend anonymous types for something like this - it's obviously an important concept in the OP's software.
Reed Copsey
It's not a great design, at the moment, I'm simply just trying to create a brain dead simple way to populate a dropdownlist on this temp form. In the future, car and truck will implement an IVehicle interface. I don't really know the best way to setup an interface on datatables in a linq query, but I'll cross that bridge when I get to it.
Shawn
@`Reed Copsey`: Agreed. :-)
Enigmativity
A: 

Or you could use the Union operator, if they were the same type. This should also work with anonymous types that have the same members:

var vehicles = from c in db.Cars          
    select new {ID = c.ID, Name = c.Name, Company = c.Company};
vehicles.Union(from t in db.Trucks          
    select new {ID = t.ID, Name = t.Name, Company = t.Company};

presuming that the id, name and company types are the same in both car and truck.

John Gardner
Union assumes that the OP does not want duplicates, which is probably a safe assumption in this case
erash