gpt4 book ai didi

c# - C#中不同的对象列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:18 25 4
gpt4 key购买 nike

我必须区分对象列表,而不仅仅是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;


谢谢

最佳答案

使用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()的空重载来避免需要额外的类。但是,请确保您了解此决定的含义:例如,这些将在其使用的所有非显式范围内变为相等性测试功能。这可能是完美的,正是您所需要的,否则可能会导致一些意外的后果。只要确保您知道自己正在进入什么。

关于c# - C#中不同的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24901975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com