[英]Distinct List of object in 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;
謝謝
使用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()
但是,請確保您了解此決定的含義:例如,這些將在其使用的所有非顯式范圍內成為相等性測試功能。 這可能是完美的,正是您所需要的,否則可能會導致一些意外的后果。 只要確保您知道自己正在進入什么。
我要使用其他屬性,則應實現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());
您還可以覆蓋 MessageDTO
類中的Equals
:
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();
您可以使用MoreLinq庫中的擴展方法DistinctBy:
string[] source = { "first", "second", "third", "fourth", "fifth" };
var distinct = source.DistinctBy(word => word.Length);
看這里 :
我建議您使用@Matthew Haugen的解決方案
如果您不想為此創建新類,則可以通過使用按不同字段對列表進行分組,然后選擇該組中的第一項來使用LINQ。 例如:
example.(e => new { e.MsgID, e.Subject }).Select(grp => grp.FirstOrDefault());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.