如何对对象列表或对象的一个或多个属性使用 Distinct



我需要获取唯一送货地址的列表。

var shippingAddresses = ShopApi.Checkout.GetShippingAddresses(Shop.CommerceContext.AccountId).ToList();

这将为我提供一个送货地址对象的列表,但其中两个对象的 Id 列具有相同的值。如何过滤它或只获取一个值到列表中?

我的 ShippingAddress 对象如下所示。

public string Id { get; set; }
public string CustomerId { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string CountryId { get; set; }

我有一个解决方案来解决你的情况。您可以再次筛选列表,以便每个 Id 值仅获取 1 行

public class ShippingAddresses
{
    public string Id { get; set; }
    public string CustomerId { get; set; }
    public string Address { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string CountryId { get; set; }
}
List<ShippingAddresses> shippingAddresses = new List<ShippingAddresses>();
//This statement will help you only get 1 row for each ID value
shippingAddresses = shippingAddresses.GroupBy(p => p.Id).Select(p => p.First()).ToList();

在该 ShippingAddress 对象的某个位置,有一个基础数据库查询。需要修改该查询以仅包含唯一结果...喜欢这个:

(from dbo in database.ShippingAddress
 select dbo.Id).Distinct()

最新更新