user3266638
user3266638

Reputation: 449

Update object field if it doesn't exist in a list of objects?

I have 2 list of objects that look like this:

public class Object1
{
    public string Value1 {get; set;}
    public string Value2 {get; set;}
    public bool Exclude {get; set;}
}

And a second one that contains the values that I want to use to exclude values from the first object.

public class Object2
{
    public string Value1 {get; set;}
    public string Value2 {get; set;}

}

How can I write something that would set the value of Exclude to true if both Value1 and Value2 don't match both of the properties in Object2 concurrently?

List<Object1> object1 = new List<Object1>();
List<Object2> object2 = new List<Object2>();

Upvotes: 0

Views: 505

Answers (4)

Rufus L
Rufus L

Reputation: 37020

Another way to do this would be to implement a comparison method on the Object1 class that takes in an Object2 and returns true if the properties match:

public class Object1
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public bool Exclude { get; set; }

    public bool ValuesMatch(Object2 other)
    {
        return (other != null) &&
               Value1 == other.Value1 &&
               Value2 == other.Value2;
    }
}

Then you can use this method in your Linq statement:

object1.ForEach(o1 => o1.Exclude = object2.Any(o1.ValuesMatch));

Upvotes: 0

ctoph
ctoph

Reputation: 155

If you have two lists, this should work:

foreach (var obj1 in object1)
{
    obj1.Exclude = true;
    foreach (var obj2 in object2)
    {
        if (obj1.Value1.Equals(obj2.Value1)
            || obj1.Value1.Equals(obj2.Value2)
            || obj1.Value2.Equals(obj2.Value1)
            || obj1.Value2.Equals(obj2.Value2))
        {
            obj1.Exclude = false;
            break;
        }
    }
}

this will initialize Exclude to true, then loop through the Object1 list and compare both its values to both the values of every Object2 in the object2 list. If it finds a match, it sets exclude to false and breaks the inner loop because it doesn't need to look anymore. If it makes it all the way through, Exclude stays true.

Upvotes: 0

JuanR
JuanR

Reputation: 7783

If what you are looking to do is mark the objects from the first list for exclusion because there is no object that matches Value1 and Value2 properties in the second list, you can try a ForEach:

object1.ForEach(o1 => o1.Exclude = !object2.Any(o2 => o2.Value1 == o1.Value1 && o2.Value2 == o1.Value2));

Upvotes: 0

Christos
Christos

Reputation: 53958

You could try something like the following:

if(!listOfObject2.Any(x => x.Value1 == object1.Value1 
                        && x.Value2 == object1.Value2)
)
{
    object1.Exclude = true;
}

In the above snippet, listOfObject2 is of type List<Object2> and object1 of type Object1.

Upvotes: 2

Related Questions