使用LINQ从表中只获取一个值

时间:2012-10-05 10:54:14

标签: linq select subquery

我有一个客户表和一个地址表(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;

我在客户端的DB中为不同的地址获取相同的地址字符串,而我只想获得一个。

2 个答案:

答案 0 :(得分:2)

由于您已按客户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();

答案 1 :(得分:0)

将您的foreach替换为

var result =
    customerAdress.Any(ad => ad.Address != null) 
    ? customerAdress.Last(ad => ad.Address != null).Address
    : default(string);