Sử dụng GroupBy, nhưng xin lưu ý rằng GroupBybạn nên Nhóm theo tất cả các cột vì nếu bạn chỉ nhóm theo Idnó sẽ không xóa các mục trùng lặp luôn. Ví dụ, hãy xem xét ví dụ sau:
List<Item> a = new List<Item>
{
new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
new Item {Id = 2, Name = "Item2", Code = "IT00002", Price = 200},
new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
new Item {Id = 1, Name = "Item1", Code = "IT00001", Price = 100},
new Item {Id = 3, Name = "Item3", Code = "IT00003", Price = 150},
new Item {Id = 3, Name = "Item3", Code = "IT00004", Price = 250}
};
var distinctItems = a.GroupBy(x => x.Id).Select(y => y.First());
Kết quả cho nhóm này sẽ là:
{Id = 1, Name = "Item1", Code = "IT00001", Price = 100}
{Id = 2, Name = "Item2", Code = "IT00002", Price = 200}
{Id = 3, Name = "Item3", Code = "IT00003", Price = 150}
Điều này là không chính xác bởi vì nó được coi {Id = 3, Name = "Item3", Code = "IT00004", Price = 250}là trùng lặp. Vì vậy, truy vấn chính xác sẽ là:
var distinctItems = a.GroupBy(c => new { c.Id , c.Name , c.Code , c.Price})
.Select(c => c.First()).ToList();
3.Override Equalvà GetHashCodetrong lớp mục:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public int Price { get; set; }
public override bool Equals(object obj)
{
if (!(obj is Item))
return false;
Item p = (Item)obj;
return (p.Id == Id && p.Name == Name && p.Code == Code && p.Price == Price);
}
public override int GetHashCode()
{
return String.Format("{0}|{1}|{2}|{3}", Id, Name, Code, Price).GetHashCode();
}
}
Sau đó, bạn có thể sử dụng nó như thế này:
var distinctItems = a.Distinct();