根据属性从列表中删除重复的对象

时间:2014-04-30 17:05:04

标签: c# linq list

SchematicElevation个对象的列表中,如何使用LINQ删除具有相同属性的对象。

public class SchematicElevation
{
    public double Elevation { get; set; }
    public int ColumnId { get; set; }
}

var se1 = new SchematicElevation { ColumnId = 2, Elevation = 300 };
var se2 = new SchematicElevation { ColumnId = 3, Elevation = 300 };
var se3 = new SchematicElevation { ColumnId = 4, Elevation = 300 };
var se4 = new SchematicElevation { ColumnId = 4, Elevation = 300 };
var se5 = new SchematicElevation { ColumnId = 4, Elevation = 300 };

var SchematicElevations = new List<SchematicElevation> { se1, se2, se3, se4, se5}

最终结果如下:

List: {se1, se2, se3}

我想使用 LINQ 并使用 GroupBy 进行此操作。

2 个答案:

答案 0 :(得分:2)

您应该直接在SchematicElevation上或通过IEqualityComparer<T>实现相等性。例如,使用hash algorithm from Jon Skeet

public class SchematicElevation : IEquatable<SchematicElevation>
{
    public double Elevation { get; set; }
    public int ColumnId { get; set; }
    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = 17;
            hash = hash * 23 + Elevation.GetHashCode();
            hash = hash * 23 + ColumnId.GetHashCode();
            return hash;
        }
    }
    public override bool Equals(object other)
    {
        return Equals(other as SchematicElevation);
    }
    public bool Equals(SchematicElevation other)
    {
        return other != null && this.Elevation == other.Elevation &&
               this.ColumnId == other.ColumnId;
    }
}

然后你只需要Distinct()来获取不同的项目:

var schematicElevations = new List<SchematicElevation> {se1, se2, se3, se4, se5};
var distinct = schematicElevations.Distinct();

或者,你可以做GroupBy。这使得代码更短,但与上述不同,它不可重用或非常易于维护。例如。如果您想更改条件,则必须在使用它的任何地方更改此代码,而不仅仅是SchematicElevation类。

var schematicElevations = new List<SchematicElevation> {se1, se2, se3, se4, se5};
var distinct = schematicElevations.GroupBy(x => new { x.ColumnId, x.Elevation })
                                  .Select(g => g.First());

答案 1 :(得分:0)

我强烈建议您实施IEquatable。然后你可以使用设计用来做你想要的方法Distinct()(而不是Group By,它不是为了你想要的而做的,但仍允许你到达那里)。

var result = SchematicElevations.Distinct();