gpt4 book ai didi

linq - 使用 LINQ 从表中仅获取一个值

转载 作者:行者123 更新时间:2023-12-01 04:56:25 25 4
gpt4 key购买 nike

我有一个客户表和一个地址表(customer_id、address_forename、address_surname、address_street、address_city、address_zip、address_storedtime),其中 customer_id 作为外键。

一个客户可以有多个地址。

现在我尝试使用 LINQ 仅获取最后输入的地址,如下所示,这应该允许我将地址放入字符串中并返回:代码:

var customerAddress = (from c in myDB.address
where (c.customer_id == customerId)
select new
{
c.customer_id,
c.address_forename,
c.address_surname,
c.address_street,
c.address_city,
c.address_zip,
c.address_storedtime
}).GroupBy(g => new
{
Customer = .customer_id,
Address = g.address_forename + " " + g.address_surname + " " + g.address_street + " " + g.address_city + " " + g.address_zip
}).Select(g => new
{
g.Key.Customer,
g.Key.Address,
StoredTime = g.Max(x => x.address_storedtime)
}).Disinct();/*First();*/

string result = "";

foreach (var ad in customerAddress)
{
if (ad.Address != null)
{
result = ad.Address;
}
break;
}

return result;

我在数据库中为客户获取不同地址的相同地址字符串,而我试图只获取一个。

最佳答案

由于您已经按客户 ID 进行过滤,因此不需要分组子句。您应该能够只为客户降序排列结果并更简单地预测地址。

var customerAddress = (from c in myDB.address
where (c.customer_id == customerId)
orderby c.address_storedtime descending
select c.address_forename + " " + c.address_surname + " " + c.address_street + " " + c.address_city + " " + c.address_zip)
.FirstOrDefault();

关于linq - 使用 LINQ 从表中仅获取一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12744735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com