C# Appending Linq Queries of Same Type
I have two linq queries that I run on two different tables, Car and Truck. From these queries I select 开发者_StackOverflowthe 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?
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.
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.
精彩评论