[英]c# Check if custom class is in list<t>
我有一個名為List<Notifications>
的自定義類的List<Notifications>
。
該類如下:
public class Notification
{
public enum Type {
Promotion,
Other
}
public string ID { get; set; }
public string Headline { get; set; }
public string Detail { get; set; }
public Type NotificationType { get; set; }
}
在將Notification類的實例添加到我的自定義列表之前,我想檢查它是否已經在列表中。
實現此目標的最佳方法是什么?
您可以使用1.) Contains
,但是必須重寫Equals
(+ GethashCode
)。
bool contains = list.Contains(someNotificationInstance);
例如:
public class Notification
{
public enum Type {
Promotion,
Other
}
public string ID { get; set; }
public string Headline { get; set; }
public string Detail { get; set; }
public Type NotificationType { get; set; }
public override bool Equals(object obj)
{
return obj is Notification && string.Equals(ID, ((Notification)obj).ID);
}
public override int GetHashCode()
{
return ID == null ? 0 : ID.GetHashCode();
}
}
2.)另一個選項是為Contains
提供自定義IEqualityComparer<Notification>
:
public class NotificationComparer : IEqualityComparer<Notification>
{
public bool Equals(Notification x, Notification y)
{
return x.ID == y.ID;
}
public int GetHashCode(Notification obj)
{
return obj.ID == null ? 0 : obj.ID.GetHashCode();
}
}
這樣,您無需修改原始類。 您可以通過以下方式使用它:
bool contains = list.Contains(someInstance, new NotificationComparer());
3.)可能最簡單的方法是使用Enumerable.Any
:
bool contains = list.Any(n => someInstance.ID == n.ID);
4.)如果集合中始終不允許重復,則最有效的方法是使用集合。 然后,您可以對HashSet<T>
使用第一種或第二種方法:
var set = new HashSet<Notification>(new NotificationComparer());
set.Add(instance1);
bool contains = !set.Add(instance2);
您可以使用Contains
方法進行檢查。
if (!mylist.Select(l => l.ID).Contains(mynewid)) {
var item = new Notifcation();
item.ID = mynewid;
item..... // fill the rest
mylist.Add(item);
}
也許更好的方法是使用Dictionary 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.