Add items to a collection if the collection does NOT already contain it by comparing a property of the items?

C#LinqCollectionsContains

C# Problem Overview


Basically, how do I make it so I can do something similar to: CurrentCollection.Contains(...), except by comparing if the item's property is already in the collection?

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?

C# Solutions


Solution 1 - C#

You start by finding which elements are not already in the collection:

var newItems = DownloadedItems.Where(x => !CurrentCollection.Any(y => x.bar == y.bar));

And then just add them:

foreach(var item in newItems)
{
    CurrentCollection.Add(item);
}

Note that the first operation may have quadratic complexity if the size of DownloadedItems is close to the size of CurrentCollection. If that ends up causing problems (measure first!), you can use a HashSet to bring the complexity down to linear:

// 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);
}

Solution 2 - C#

You can use Enumerable.Except:

It will compare the two lists and return elements that appear only in the first list.

CurrentCollection.AddRange(DownloadedItems.Except(CurrentCollection));

Solution 3 - C#

Using R.Martinho Fernandes method and converting to 1 line:

CurrentCollection.AddRange(DownloadedItems.Where(x => !CurrentCollection.Any(y => y.bar== x.bar)));

Solution 4 - C#

You can call the Any method and pass a value to compare to whatever property of the type of object in the collection

if (!CurrentCollection.Any(f => f.bar == someValue))
{
    // add item
}

a more complete solution could be:

DownloadedItems.Where(d => !CurrentCollection.Any(c => c.bar == d.bar)).ToList()
    .ForEach(f => CurrentCollection.Add(f));

Solution 5 - C#

Or using All

CurrentCollection
    .AddRange(DownloadedItems.Where(x => CurrentCollection.All(y => y.bar != x.bar)));

Solution 6 - C#

One thing that you can do also i think it is the easiest way is to une a HashSet instead of a List, by default the HashSet don't add redundant values.

Solution 7 - C#

    List<int> current = new List<int> { 1, 2 };
    List<int> add = new List<int> { 2, 3 };
    current.AddRange(add.Except(current));

This will result in 1,2,3, using the default comparing.
This will also work for Foo if you change the compare behaviour:

    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()
    }

You could also implement an IEqualityComparer<Foo>, and pass it as second parameter to 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();
        }
    }

Solution 8 - C#

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)....

Solution 9 - C#

var newItems = DownloadedItems.Where(i => !CurrentCollection.Any(c => c.Attr == i.Attr));

Solution 10 - C#

You could do it like this:

CurrentCollection.Any(x => x.bar == yourGivenValue)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmichaelView Question on Stackoverflow
Solution 1 - C#R. Martinho FernandesView Answer on Stackoverflow
Solution 2 - C#YangaView Answer on Stackoverflow
Solution 3 - C#JumpingJezzaView Answer on Stackoverflow
Solution 4 - C#hunterView Answer on Stackoverflow
Solution 5 - C#Janis S.View Answer on Stackoverflow
Solution 6 - C#Khalil LiraquiView Answer on Stackoverflow
Solution 7 - C#Maik van den HengelView Answer on Stackoverflow
Solution 8 - C#Milan HettnerView Answer on Stackoverflow
Solution 9 - C#Bala RView Answer on Stackoverflow
Solution 10 - C#ub1kView Answer on Stackoverflow