通过使用Linq从列表

时间:2016-01-12 07:06:19

标签: c# linq

我有一个列表的代码,我可以在列表中有重复的记录。 在最终结果中,我需要删除重复的条目并使它们唯一。我编写了如下代码,

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;

欢迎任何建议。

2 个答案:

答案 0 :(得分:1)

您的代码有错误。不是向列表中添加三个不同的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());

答案 1 :(得分:-1)

我建议你使用Distinct()函数。 https://msdn.microsoft.com/library/bb348436(v=vs.100).aspx

它看起来像这样:

SELECT e.id, e.name, e.salary, e.did, d.dname
FROM [dbo].[Table_1] e , [dbo].[Table_2] d
WHERE  e.did = d.did
GROUP BY e.id, e.name, e.salary, e.did, d.dname;