My Object structure is like this
我的对象结构是这样的
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; }
}
And I have a list of this object like this
我有这样一个对象的列表
List<ProductToBids> productsInThisFairs = new List<ProductToBids>();
productsInThisFairs = FillData();
Now I want to select all rows from this list where combination of BiddedUserId
and ProductId
is unique, and if there is multiple rows satisfying this condition I want to select only the row which have the highest value in column BidAmount
How can I achieve this? I have tried doing this by Grouping the items first by two columns and taking max value later Code was like this
现在,我想从这个列表中选择所有的行,其中BiddedUserId和ProductId的组合是唯一的,如果有多个行满足这个条件,我想只选择列BidAmount中具有最高值的行,我该如何实现它呢?我尝试过先将条目分组为两列,然后取max value后面的代码是这样的
productsInThisFairs.DistinctBy(x=>new {x.ProductId,x.BiddedUserId }).ToList()
but understood that this will return only those two columns in the list all other columns will be discarded. Can anyone please point out what will be the correct way to achieve this?
但是,理解这将只返回列表中的这两列,所有其他列都将被丢弃。谁能指出实现这一目标的正确方法是什么?
1 个解决方案
#1
3
You could try a group by of your list items based on their ProductId
and BidderUserId
and then for each group to pick up the record with the highest BidAmount
. The latter can be done by ordering the group items in a descending order based on their BidAmount
and then pick the first item of each group.
您可以根据它们的ProductId和BidderUserId对列表项进行分组,然后对每个组使用最高的BidAmount获取记录。后者可以通过按其BidAmount的降序顺序排列组项,然后选择每个组的第一项。
var result = productsInThisFairs.GroupBy(prd=>new { prd.ProductId, prd.BiddedUserId})
.Select(grp => grp.OrderByDescending(item=>item.BidAmount)
.FirstOrDefault());
#1
3
You could try a group by of your list items based on their ProductId
and BidderUserId
and then for each group to pick up the record with the highest BidAmount
. The latter can be done by ordering the group items in a descending order based on their BidAmount
and then pick the first item of each group.
您可以根据它们的ProductId和BidderUserId对列表项进行分组,然后对每个组使用最高的BidAmount获取记录。后者可以通过按其BidAmount的降序顺序排列组项,然后选择每个组的第一项。
var result = productsInThisFairs.GroupBy(prd=>new { prd.ProductId, prd.BiddedUserId})
.Select(grp => grp.OrderByDescending(item=>item.BidAmount)
.FirstOrDefault());