【发布时间】:2015-10-12 08:50:08
【问题描述】:
如何从项目列表中消除重复的项目(时间戳)。我有一个带有重复时间戳的项目列表。我想填写另一个响应列表,并通过 For each 循环消除基于唯一时间戳的重复记录。退货商品列表中只能有一个时间戳。
public class InventoryDetails
{
public int InventoryDetailsId { get; set; }
public int ItemName { get; set; }
public int Price { get; set; }
public DateTime Timestamp { get; set; }
}
public class InventoryDetailsResponse
{
public int InventoryDetailsId { get; set; }
public int ItemName { get; set; }
public int Price { get; set; }
public DateTime Timestamp { get; set; }
}
来自数据库的样本库存数据
101 , Item1, 500, 2015-06-24 16:00:03
102、第2、125、2015-07-01 01:20:03
103、Item1、500、2015-06-24 16:00:03
104、Item3、340、2015-07-04 09:10:12
105、Item4、059、2015-06-24 12:23:03
106、Item1、500、2015-06-24 16:00:03
107、第5、845、2015-07-11 15:30:03
// 需要根据时间戳去除重复记录。
public List<InventoryDetailsResponse> GetInventory()
{
List<InventoryDetails> result = FromDatabase();
var list = new List<InventoryDetailsResponse>();
foreach (InventoryDetails match in result)
{
var tc = new InventoryDetailsResponse
{
InventoryDetailsId = match.InventoryDetailsId,
ItemName = match.ItemName,
Price = match.Price,
Timestamp = match.Timestamp // Duplicate timestamp in database.
};
list.Add(tc);
}
return list;
}
【问题讨论】:
-
您要消除内存中或查询内部的重复项吗?
-
如果你想在查询后做,你可以创建一个HashSet
,在你的foreach中添加每个时间戳并在列表周围添加一个条件。添加以检查时间戳是否没有已经遇到了
标签: c# .net linq foreach lambda