使用Linq进行分组,从列表中获取唯一记录
本文关键字:列表 获取 唯一 记录 Linq 使用 | 更新日期: 2023-09-27 18:30:04
我有下面的列表代码,其中可以有列表的重复记录。在最后的结果中,我需要删除重复的条目,并使它们唯一。我已经写了如下代码,
public class BusLocation
{
public string Latitude { get; set; }
public string Longitude { get; set; }
public string BusNumber { get; set; }
public Int64 ScheduleId { get; set; }
public Int64 TripId { get; set; }
}
List<BusLocation> _BusLocation=new List<BusLocation>();
BusLocation loc = new BusLocation();
loc.BusNumber = "123";
loc.Latitude = "12.1234";
loc.Longitude = "44.1234";
loc.ScheduleId = 77;
loc.TripId = 1678;
_BusLocation.Add(loc);
loc.BusNumber = "123";
loc.Latitude = "12.1234";
loc.Longitude = "44.1234";
loc.ScheduleId = 77;
loc.TripId = 1678;
_BusLocation.Add(loc);
loc.BusNumber = "123";
loc.Latitude = "12.1334";
loc.Longitude = "44.1334";
loc.ScheduleId = 78;
loc.TripId = 1679;
_BusLocation.Add(loc);
var result1 = _BusLocation
.GroupBy(lat => lat.Latitude)
.Select(grp => grp.ToList())
.ToList();
但它给了我错误的结果,因为最后的记录重复了3次,我想把它作为列入名单
loc.BusNumber = "123";
loc.Latitude = "12.1234";
loc.Longitude = "44.1234";
loc.ScheduleId = 77;
loc.TripId = 1678;
loc.BusNumber = "123";
loc.Latitude = "12.1334";
loc.Longitude = "44.1334";
loc.ScheduleId = 78;
loc.TripId = 1679;
欢迎提出任何建议。
您的代码有一个错误。不向列表中添加三个不同的BusLocation
实例,而是将同一实例添加三次。您可以通过使用初始化程序来修复代码并使其更加简洁:
List<BusLocation> _BusLocation = new List<BusLocation>() {
new BusLocation {
BusNumber = "123",
Latitude = "12.1234",
Longitude = "44.1234",
ScheduleId = 77,
TripId = 1678
},
new BusLocation {
Latitude = "12.1234",
Longitude = "44.1234",
ScheduleId = 77,
TripId = 1678
},
new BusLocation {
BusNumber = "123",
Latitude = "12.1334",
Longitude = "44.1334",
ScheduleId = 78,
TripId = 1679
}
};
要删除重复项,您需要定义什么是重复项。您可以通过创建一个IEqualityComparer<BusLocation>
类来实现这一点:
class BusLocationEqualityComparer : IEqualityComparer<BusLocation> {
public Boolean Equals(BusLocation x, BusLocation y) {
return x.BusNumber == y.BusNumber
&& x.Latitude == y.Latitude
&& x.Longitude == y.Longitude;
}
public Int32 GetHashCode(BusLocation obj) {
unchecked {
const Int32 Multiplier = -1521134295;
var hash = -1901080290;
hash = hash*Multiplier + obj.Latitude?.GetHashCode() ?? 0;
hash = hash*Multiplier + obj.Longitude?.GetHashCode() ?? 0;
hash = hash*Multiplier + obj.BusNumber?.GetHashCode() ?? 0;
return hash;
}
}
}
在这里,相等被定义为具有相同的总线编号、纬度和经度。然而,由于您使用字符串表示纬度和经度,我不确定这是否有效,但我将把它留给您。
要获得不同的巴士位置,您可以使用LINQ:
var distinctBusLocations = _BusLocation.Distinct(new BusLocationEqualityComparer());
我建议您使用Distinct()函数。https://msdn.microsoft.com/library/bb348436(v=vs.100).aspx
它看起来像这样:
var result1 = _BusLocation.GroupBy(lat => lat.Latitude).Select(grp => grp.ToList()).ToList().Distinct();