如何从项目列表中消除重复的项目(时间戳)。我有一个重复时间戳的项目列表。我想填充另一个响应列表并根据每个循环的唯一时间戳消除重复记录。退货项目清单中只应出现一个时间戳。
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,Item2,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,Item5,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;
}
答案 0 :(得分:5)
直接使用Linq:
var myUniqueRecordsByTimestamp = GetInventory()
.GroupBy(x => x.Timestamp)
.Select(g => g.First());
GroupBy
操作会返回IEnumerable
个IGrouping
个项目(IEnumerables
也是如此)。
Source Answer来自类似但不重复的问题。
答案 1 :(得分:2)
我将此用于同一目的,就像一个魅力:
List<InventoryDetails> list = result.GroupBy(x => x.Timestamp).Select(y => y.First()).ToList();
它根据指定的属性(此处为Timestamp)对项目进行分组,并使用每个组的第一项构建新列表。
答案 2 :(得分:0)
您可以使用LINQ:
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);
}
var res = list.GroupBy(item => item.Timestamp).Select(g => g.First()).ToList();
return res;
}
答案 3 :(得分:-3)
您可以覆盖Equals
课程的InventoryDetails
,例如:
class InventoryDetails {
public override Equals(object obj) {
if (obj is InventoryDetails) {
InventoryDetails details = (InventoryDetails)obj;
return details.ItemName == this.ItemName && details.Price == this.Price && details.Timestamp == this.Timestamp;
}
return false;
}
}
之后,您可以使用List<InventoryDetails>.Distinct()
删除重复的条目,因为现在认为具有相同Timestamp
的所有条目都是相同的。