簡體   English   中英

LINQ 加入來自不同類別的值

[英]LINQ joining values from different classes

我是 LINQ 的新手,如果有人問我的問題,我很抱歉

我有2節課

public class Person
{
    int ID {get;set;}
    string FirstName {get;set;}
    string LastName {get;set;}
}

public class House
{
    int ID {get;set;}
    string Address {get;set;}
    string ZipCode {get;set;}
    int PersonId {get;set;}
}

我將房屋清單保存在 IEnumerable List 中

IEnumerable<House> ListHouses = GetAllHouses();

GetAllHouses 從數據庫中返回房屋列表

我想在 LINQ 中使用 Lamda select 以執行以下操作

var st = ListHouses .Select(h => new
{
    id = h.ID,
    Address= h.Address,
    Zip= h.ZipCode ,
    PersonFirstName = GetPersonByID(h.PersonId ).FirstName, 
    PersonLastname = GetPersonByID(h.PersonId ).lastname

});

其中 GetPersonByID 返回具有給定 ID 的Person類型的 object。 然后我記下他的名字和姓氏。

我的問題是:

而不是為變量(personFirstName 和 PersonLastName)獲取 Person 2 次,有沒有一種方法可以獲取它一次然后使用它。 就像是

PersonForId = GetPersonByID(h.PersonId)
PersonFirstName =  PersonLastName.FirstName,
PersonLastname = PersonLastName.lastname

我正在尋找類似於 Join in SQL 的內容,您可以在其中加入另一個表中的值。

非常感謝您的幫助

你非常接近,使用你的代碼(並公開 House 和 Person 的所有屬性):這是一個使用 LINQ Join 方法的方法:

var st = GetAllHouses().Join(GetAllPersons(),
    outerKey => outerKey.PersonId,
    innerKey => innerKey.ID,
    (house, person) => new
    {
        house.ID,
        house.Address,
        house.ZipCode,
        PersonFirstName = person.FirstName,
        PersonLastname = person.LastName
    });

注意:我推薦 GetAllPersons() 和 GetAllHouses() 方法返回 IQueryable 而不是 IEnumerable。 這樣做將構建表達式(包括連接),這意味着 LINQ-to-SQL(或實體)將構建包含 JOIN 的正確 SQL 語句,而不是枚舉 collections然后連接。

有關此類的其他信息,請參見此處: Returning IEnumerable<T> vs. IQueryable<T>

using System;
using System.Linq;

class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class Order
{
    public int ID { get; set; }
    public string Product { get; set; }
}

class Program
{
    static void Main()
    {
    // Example customers.
    var customers = new Customer[]
    {
        new Customer{ID = 5, Name = "Sam"},
        new Customer{ID = 6, Name = "Dave"},
        new Customer{ID = 7, Name = "Julia"},
        new Customer{ID = 8, Name = "Sue"}
    };

    // Example orders.
    var orders = new Order[]
    {
        new Order{ID = 5, Product = "Book"},
        new Order{ID = 6, Product = "Game"},
        new Order{ID = 7, Product = "Computer"},
        new Order{ID = 8, Product = "Shirt"}
    };

    // Join on the ID properties.
    var query = from c in customers
            join o in orders on c.ID equals o.ID
            select new { c.Name, o.Product };

    // Display joined groups.
    foreach (var group in query)
    {
        Console.WriteLine("{0} bought {1}", group.Name, group.Product);
    }
    }
}

Output

山姆買了書戴夫買了游戲 Julia 買了電腦蘇買了襯衫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM