I have code like this
var results = (from c in Customers
join o in Orders
on c.Id equals o.CustomerId
join p in Products
on p.Id equals o.ProductId
select new
{
CustomerId = c.Id, // this is a GUID
OrderId = o.Id, // this is a GUID
ProductName = p.ProductName,
}).ToList();
Let’s say I want to get a list of all customer Ids that orders a product that has name = foo
My problem is that because its an anonymous type, how can I refer product name in any Linq query that I want to run on results?
The compiler’s type inference takes care of it for you. The complete answer to your question:
or
EDIT
Some musings on type inference
To select the lengths from a sequence of strings called
list, you can callSelecteither using classic static method syntax or as an extension method:Thanks to type inference, you don’t need the type arguments:
In this case, the compiler can prove that the type arguments are
stringandintby looking at the method arguments, and it supplies these type arguments on your behalf without your having to type them into the source code.For anonymous types, you can’t provide the first type argument, because the type doesn’t have a name for you to use in the source code (that’s what “anonymous” means, after all: “without a name”). (You can see therefore that anonymous types and type inference were both critical — and closely related — prerequisites to implementing linq in the first place.)
If you check out the IL for the anonymous type example above, you’ll see that the compiler has in fact given the type a name (which contains characters that are illegal in C# identifiers). When you call
Select, the compiler deduces from the type of the enumerable (IEnumerable<CrazilyNamedAnonymousType>) that the first type argument should be the anonymous type, and, as with the string example, it supplies that value on your behalf.