score:0

Accepted answer

maybe you’re looking for the let keyword?

var persons = 
    from _person in people
    let placeid = 
    (
        from _peopleplaces in peopleplace
        where _person.id == _peopleplaces.personid 
        select _peopleplaces.placeid
    ).firstordefault()
    let placename =
    (
        from _places in places
        where _places.id == placeid 
        select _places.name
    ).firstordefault()
    select new
    {
        id = _person.id,
        name = _person.name,
        nationality = _person.nationality,
        age = _person.age,
        placeid = placeid,
        placename = placename,
    };

edit: as @sambomartin correctly mentioned below, you need to consider what would happen if there is no entry in peopleplace for a specific person. under the above query, such persons are still returned in the final result, with a placeid and placename of null.

c# allows equality comparison between an int and a int?; if the latter is null, the comparison would always evaluate to false. thus, when placeid is null, no entry from places would satisfy the _places.id == placeid condition (assuming the id field is not nullable), and placename would evaluate to null as well.

if you do not want such persons in your final result, you could amend your query by adding where clauses:

var persons = 
    from _person in people
    let placeid = 
    (
        from _peopleplaces in peopleplace
        where _person.id == _peopleplaces.personid 
        select _peopleplaces.placeid
    ).firstordefault()
    where placeid != null   // ensure that the person has an associated place
    let placename =
    (
        from _places in places
        where _places.id == placeid 
        select _places.name
    ).firstordefault()
    where placename != null   // ensure that the place appears in the primary table
    select new
    {
        id = _person.id,
        name = _person.name,
        nationality = _person.nationality,
        age = _person.age,
        placeid = placeid,
        placename = placename,
    };

score:3

you cant use the placeid until it's been calculated, i.e. when its enumerated.

there's nothing to stop you querying the three objects in a single expression, e.g.

var people = from p in persons
             from ppl in personplaces
             from pl in places
             where p.id == ppl.personid
             && ppl.placeid == pl.id
             select new { name=p.name, placename=pl.name}

sorry for formatting, it's difficult on ipad.

hth

sam


Related Query

More Query from same tag