使用linq在表中查找部分重复项

时间:2015-09-16 09:27:44

标签: c# linq

我想在下面的Trip表中找到部分重复记录:

<table>
<tr>
<td> Port </td><td>TripId</td><td>StatusId</td></tr>
<tr><td> 475210 </td><td>500013</td><td>13</td></tr>
<tr><td> 475211</td><td>500013</td><td>13</td></tr>
<tr><td> 475212</td><td>500013</td><td>13</td></tr>
<tr><td> 475213</td><td>500012</td><td>13</td></tr>
<tr><td> 475214</td><td>500012</td><td>13</td></tr>
<tr><td> 475215</td><td>500045</td><td>13</td></tr>
<tr><td> 475216</td><td>500045</td><td>13</td></tr>
<tr><td> 475217</td><td>500045</td><td>13</td></tr>
<tr><td> 475218</td><td>500045</td><td>13</td></tr>
<tr><td> 475218</td><td>500045</td><td>12</td></tr>
</tr>
</table>

最后2条记录不应该发生(任何一对Port / TripId在我的表中不应该有不同的状态),我想在整个表中找到所有类似的记录。上面显示的表格只是我旅行表中的一个摘录,其中包含了更多的记录。这些作为custum集合加载到内存中

public  class Trip
{
   public string Port {get;set;}
   public string TripId {get;set;}
   public string StatusId {get;set;}
}

提前谢谢

2 个答案:

答案 0 :(得分:3)

您可以结合使用分组,where条件并选择所需的值:

YourList
.GroupBy(c => new { c.TripId, c.Port })
.Where(grp => grp.Count() > 1)
.Select(grp => new { Port = grp.Key.Port, TripId = grp.Key.TripId });

完整的工作示例:

public class Trip
{
    public string Port { get; set; }
    public string TripId { get; set; }
    public string StatusId { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        IList<Trip> tripList = new List<Trip>();

        tripList.Add(new Trip() { TripId = "123", Port = "1" });
        tripList.Add(new Trip() { TripId = "124", Port = "2" });
        tripList.Add(new Trip() { TripId = "124", Port = "3" });
        tripList.Add(new Trip() { TripId = "126", Port = "4" });
        tripList.Add(new Trip() { TripId = "126", Port = "4" });

        var doubleTrip = tripList
            .GroupBy(c => new { c.TripId, c.Port })
            .Where(grp => grp.Count() > 1)
            .Select(grp => new { Port = grp.Key.Port, TripId = grp.Key.TripId });

        foreach (var d in doubleTrip)
        {
            Console.WriteLine("TripId: {0}, Port: {1}", d.TripId, d.Port);
        }

        Console.ReadLine();
    }

答案 1 :(得分:0)

您可以使用IEqualityComparer。您的类实现可能如下所示。

class DistinctItemComparer : IEqualityComparer<Trip> {

public bool Equals(Item x, Item y) {
    return x.Port == y.Port &&
        x.TripId== y.TripId;
}

public int GetHashCode(Trip obj) {
    return obj.Port.GetHashCode() ^
        obj.TripId.GetHashCode();
}

}

然后你可以打电话来获取不同的记录 -

var distinctRecords = YourList.Distinct(new DistinctItemComparer());