[英]Select distinct items by combination of two columns and where Value of third column is max- LINQ
我的對象結構是這樣的
public class ProductToBids
{
public int BidAmount { get; set; }
public DateTime? BidDate { get; set; }
public int BiddedUserId { get; set; }
public string BidderEmail { get; set; }
public string bidderName { get; set; }
public int BidStatus { get; set; }
public int FairId { get; set; }
public string ProductDescription { get; set; }
public int ProductId { get; set; }
public string ProductName { get; set; }
}
我有一個這樣的對象列表
List<ProductToBids> productsInThisFairs = new List<ProductToBids>();
productsInThisFairs = FillData();
現在,我想從此列表中選擇BiddedUserId
和ProductId
組合是唯一的所有行,並且如果有多個行滿足此條件,我只想選擇BidAmount
列中具有最高值的行,我該如何實現? 我嘗試通過將項目首先按兩列進行分組,然后再取最大值來進行此操作,代碼如下所示
productsInThisFairs.DistinctBy(x=>new {x.ProductId,x.BiddedUserId }).ToList()
但可以理解,這只會返回列表中的這兩列,而所有其他列都將被丟棄。 任何人都可以指出實現此目標的正確方法是什么?
您可以根據列表項的ProductId
和BidderUserId
嘗試對它們進行BidderUserId
,然后讓每個組選擇具有最高BidAmount
的記錄。 后者可以通過根據組項目的BidAmount
降序對組項目進行排序,然后選擇每個組的第一項來完成。
var result = productsInThisFairs.GroupBy(prd=>new { prd.ProductId, prd.BiddedUserId})
.Select(grp => grp.OrderByDescending(item=>item.BidAmount)
.FirstOrDefault());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.