我已经在下面的linq查询中使用了一些表来获取准确的数据。
(from row in
(from c in DbContext.Customer
join cd in DbContext.CustomerDetails
on c.Customer_Id equals cd.CustomerDetail_CustomerId
join cp in DbContext.ProductPurchases
on cd.CustomerDetail_OrgID equals cp.ProductPurchase_OrgID
where cd.CustomerDetail_OrgId == OrganizationID --organization Id is common
&& c.Customer_Org_Id == OrganizationID
&& cp.ProductPurchase_OrgID == OrganizationID
orderby cd.CustomerDetail_CreatedDate descending
select new { c, cd, cp })
select new CustomerDTO
{
CustomerId = row.cpd.CustomerDetail_CustomerID,
CustomerName = row.c.Customer_LastName+", "+row.c.Customer_FirstName,
}).ToList();
我在CustomerDetail记录中有一个小问题,我只想根据CustomerId从CustomerDetail中获得不同的记录。
CustomerDetail可以为同一CustomerId拥有多个记录
请建议我如何过滤查询以仅从CustomerDetail表中获取不同的记录
谢谢,
最佳答案
LINQ提供了Distinct
方法。但是,它默认使用默认的相等比较器,也可以使用您指定的可选比较器。
我建议不要使用匿名类型,而是使用属性CustomerId和CustomerName定义一个类,然后覆盖Equals。
public class DistinctCustomer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null)) return false;
if (ReferenceEquals(this, obj)) return true;
var other = obj as DistinctCustomer;
if (other == null) return false;
return CustomerId == other.CustomerId;
}
public override int GetHashCode()
{
return CustomerId.GetHashCode();
}
}
然后
(from row in
(from c in DbContext.Customer
join cd in DbContext.CustomerDetails
on c.Customer_Id equals cd.CustomerDetail_CustomerId
join cp in DbContext.ProductPurchases
on cd.CustomerDetail_OrgID equals cp.ProductPurchase_OrgID
where cd.CustomerDetail_OrgId == OrganizationID --organization Id is common
&& c.Customer_Org_Id == OrganizationID
&& cp.ProductPurchase_OrgID == OrganizationID
orderby cd.CustomerDetail_CreatedDate descending
select new { c, cd, cp })
select new DistinctCustomer
{
CustomerId = row.cpd.CustomerDetail_CustomerID,
CustomerName = row.c.Customer_LastName+", "+row.c.Customer_FirstName,
}).Distinct().ToList();
关于c# - 如何在LINQ中获得独特的值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10696316/