[英]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.