esastincy
esastincy

Reputation: 1627

LINQ Select Many question

Can you use SelectMany in a query against your DB and if you can, what type does the column need to be in order to do this? I am messing around with LINQPad and anytime I try to use SelectMany I get an error, and from what I am reading it sounds like the type in your lambda expression has to be a collection.

Upvotes: 0

Views: 894

Answers (2)

BrokenGlass
BrokenGlass

Reputation: 161002

SelectMany projects each element of a sequence (i.e. a property of an object that is an enumeration or list) into an IEnumerable<T> and flattens the resulting sequence of sequences into a single sequence / IEnumerable<T>.

Having said that it could be applicable in i.e. a Linq to Entities environment - you could i.e. select select the navigation properties (related entities) of multiple entities and spit them out in a single list.

Upvotes: 0

DaveShaw
DaveShaw

Reputation: 52808

Houses.SelectMany(h => h.HousesPersons.Select(hp => hp.Person.Name))

If you have 3 Tables. Houses, HousesPersons and Persons. Houses has a One->Many relationship with Persons using HousesPersons to store HouseId and PersonId.

This query will get you a list of all persons in all houses in a flat list, rather than grouped by House.

EDIT: Sorry I can't get AdventureWorks to work on my machine to use a text book example.

Upvotes: 1

Related Questions