C#中的linq lambda join和select语法

5
我正在寻找Msql查询的对应方法:
SELECT per.*,add.addressDescription FROM Persons per 
       JOIN Address add ON per.AddressId = add.AddressId

我有以下查询:

    var query = persons.JOIN(address,per = person.addressId,add = addressId
    (per,add) => 
    new Persons{
                addressDescription = add.addressDescription,
                PersonId = per.PersonId,
                PersonFirstName = per.PersonFirstName
                PersonLastName = per.PersonLastName})

有没有一种方法可以在不单独赋值Persons的其他属性的情况下填充Persons.addressDescription?假设Persons还有10个以上的属性。

我想避免使用像这样的循环:

foreach(Person person in PersonList)
{
  foreach(Address address in AddressList)
  {
     if(person.addressId == address.addressId){
        person.addressDescription = address.addressDescription
     }
   }
}

@shA.t 你好,感谢你的回复。问题在于他们的问题只是询问如何返回Persons而不填充Persons.AddressDescription。 - user3770093
2个回答

4
var id = 1;
var query = database.Posts    // your starting point - table in the "from" statement
   .Join(database.Post_Metas, // the source table of the inner join
      post => post.ID,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
      meta => meta.Post_ID,   // Select the foreign key (the second part of the "on" clause)
      (post, meta) => new { Post = post, Meta = meta }) // selection
   .Where(postAndMeta => postAndMeta.Post.ID == id);    // where statement

谢谢您的回复,但我认为我仍然需要按照您的示例循环它。 - user3770093

4
var query = persons.join(address,
    per = person.addressId,
    add = addressId
    (per,add) => 
    {
        per.addressDescription = add.addressDescription;
        return per;
    });

哇,真的吗?这是我第一次在SELECT语句中看到RETURN。现在我会尝试一下。 - user3770093
我无法在查询内使用返回函数 =/ - user3770093
@user3770093 请展示一下你的操作,因为对我来说它是可行的。 - Gilad Green
嗨,伙计,谢谢你的解决方案!我只是有一些简单的打字错误。非常感谢你! - user3770093

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接