[英]Add items to a collection if the collection does NOT already contain it by comparing a property of the items?
基本上,我該怎么做才能做類似的事情: CurrentCollection.Contains(...)
,除了比較項目的屬性是否已經在集合中?
public class Foo
{
public Int32 bar;
}
ICollection<Foo> CurrentCollection;
ICollection<Foo> DownloadedItems;
//LINQ: Add any downloaded items where the bar Foo.bar is not already in the collection?
您首先要查找集合中還沒有哪些元素:
var newItems = DownloadedItems.Where(x => !CurrentCollection.Any(y => x.bar == y.bar));
然后添加它們:
foreach(var item in newItems)
{
CurrentCollection.Add(item);
}
請注意,如果DownloadedItems
的大小接近CurrentCollection
的大小,則第一個操作可能具有二次復雜度。 如果這最終導致問題(首先測量),您可以使用HashSet
將復雜性降低到線性:
// collect all existing values of the property bar
var existingValues = new HashSet<Foo>(from x in CurrentCollection select x.bar);
// pick items that have a property bar that doesn't exist yet
var newItems = DownloadedItems.Where(x => !existingValues.Contains(x.bar));
// Add them
foreach(var item in newItems)
{
CurrentCollection.Add(item);
}
您可以使用Enumerable.Except :
它將比較兩個列表並返回僅出現在第一個列表中的元素。
CurrentCollection.AddRange(DownloadedItems.Except(CurrentCollection));
使用 R.Martinho Fernandes 方法並轉換為 1 行:
CurrentCollection.AddRange(DownloadedItems.Where(x => !CurrentCollection.Any(y => y.bar== x.bar)));
您可以調用Any
方法並傳遞一個值以與集合中 object 類型的任何屬性進行比較
if (!CurrentCollection.Any(f => f.bar == someValue))
{
// add item
}
更完整的解決方案可能是:
DownloadedItems.Where(d => !CurrentCollection.Any(c => c.bar == d.bar)).ToList()
.ForEach(f => CurrentCollection.Add(f));
或使用All
CurrentCollection
.AddRange(DownloadedItems.Where(x => CurrentCollection.All(y => y.bar != x.bar)));
您還可以做的一件事我認為這是最簡單的方法是使用 HashSet 而不是 List,默認情況下 HashSet 不添加冗余值。
List<int> current = new List<int> { 1, 2 };
List<int> add = new List<int> { 2, 3 };
current.AddRange(add.Except(current));
這將導致 1,2,3,使用默認比較。
如果您更改比較行為,這也適用於Foo
:
public class Foo : IEquatable<Foo>
{
public Int32 bar;
public bool Equals(Foo other)
{
return bar == other.bar;
}
public override bool Equals(object obj) => Equals(obj as Foo);
public override int GetHashCode() => (bar).GetHashCode(); // (prop1,prop2,prop3).GetHashCode()
}
您還可以實現IEqualityComparer<Foo>
,並將其作為第二個參數傳遞給 except
current.AddRange(add.Except(current, new FooComparer()));
public class FooComparer : IEqualityComparer<Foo>
{
public bool Equals(Foo x, Foo y)
{
return x.bar.Equals(y.bar);
}
public int GetHashCode(Foo obj)
{
return obj.bar.GetHashCode();
}
}
internal static class ExtensionMethod
{
internal static ICollection<T> AddIfExists<T>(this ICollection<T> list, ICollection<T> range)
{
foreach (T item in range)
{
if (!list.Contains(item))
list.Add(item);
}
return list;
}
}
ICollection<Foo> CurrentCollection;
ICollection<Foo> DownloadedItems;
CurrentCollection.AddIfExists(DownloadedItems)....
var newItems = DownloadedItems.Where(i => !CurrentCollection.Any(c => c.Attr == i.Attr));
你可以這樣做:
CurrentCollection.Any(x => x.bar == yourGivenValue)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.