C#中不同的对象列表

时间:2014-07-23 04:39:19

标签: c#

我必须区分对象列表,但不仅仅是ID,因为有时两个不同的对象具有相同的ID。 我上课了:

public class MessageDTO
{

    public MessageDTO(MessageDTO a)
    {
        this.MsgID = a.MsgID;
        this.Subject = a.Subject;
        this.MessageText = a.MessageText;
        this.ViewedDate = a.ViewedDate;
        this.CreatedDate = a.CreatedDate;
    }

    public int? MsgID { get; set; }
    public string Subject { get; set; }
    public string MessageText { get; set; }
    public System.DateTime? ViewedDate { get; set; }
    public System.DateTime? CreatedDate { get; set; }
}

我如何区分清单:

List<MessageDTO> example;

由于

4 个答案:

答案 0 :(得分:5)

使用LINQ。

public class MessageDTOEqualityComparer : EqualityComparer<MessageDTO>
{
    public bool Equals(MessageDTO a, MessageDTO b)
    {
        // your logic, which checks each messages properties for whatever
        // grounds you need to deem them "equal." In your case, it sounds like
        // this will just be a matter of iterating through each property with an
        // if-not-equal-return-false block, then returning true at the end
    }

    public int GetHashCode(MessageDTO message)
    {
        // your logic, I'd probably just return the message ID if you can,
        // assuming that doesn't overlap too much and that it does
        // have to be equal on the two
    }
}

然后

return nonDistinct.Distinct(new MessageDTOEqualityComparer());

您还可以通过覆盖object.Equals(object)object.GetHashCode()并调用nonDistinct.Distinct()的空重载来避免需要额外的课程。但请确保您认识到此决策的含义:例如,这些将成为所有非显式范围使用中的相等测试函数。这可能是完美的,正是您所需要的,或者可能导致一些意想不到的后果。只要确保你知道自己要进入什么目的。

答案 1 :(得分:2)

我想使用其他属性,您应该实现IEqualityComparer接口。更多信息:msdn

class MsgComparer : IEqualityComparer<MessageDTO>
{
    public bool Equals(MessageDTO x, MessageDTO Oy)
    {
    }

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects.

    public int GetHashCode(MessageDTO m)
    {
           //it must br overwritten also
    }

}

然后:

example.Distinct(new MsgComparer());

您还可以在Equals课程中覆盖 MessageDTO

class MessageDTO 
{
    // rest of members
    public override bool Equals(object obj) 
    {
        // your stuff. See: http://msdn.microsoft.com/en-us/library/ms173147%28v=vs.80%29.aspx
    }
    public override int GetHashCode()
    {
    }
}

那就足够了:

example.Distinct();

答案 2 :(得分:1)

您可以使用MoreLinq库中的扩展方法DistinctBy:

string[] source = { "first", "second", "third", "fourth", "fifth" };
var distinct = source.DistinctBy(word => word.Length);

请参阅here

答案 3 :(得分:0)

我建议你使用@Matthew Haugen的解决方案

如果您不想为此创建新类,可以通过将不同字段的列表分组来使用LINQ,然后选择该组中的第一个项目。例如:

example.(e => new { e.MsgID, e.Subject }).Select(grp => grp.FirstOrDefault());