Johnv2020
Johnv2020

Reputation: 2146

c# linq - get elements from array which do not exist in a different array

I have two arrays idxListResponse & _index both of which have the same structure.

Each of these arrays contains a number of elements with different properties one of which is a child array called indexdata

Each element of this array has a number of properties one of which is another array called datafield. This has a number of key value pair properties.

So in essence I have a hierarchy of 3 separate arrays.

I'm looking to get the first level of the hierarchy + all elements of the 2nd level where the 3rd level items don't match, i.e. exclude only those items from the 2nd level where the 3rd level items are a match.

I've tried approaching this a number of different ways but so far I'm not getting anywhere, could anyone help.

FYI - here's my latest attempt

var q = idxListResponse.Index.Where(a =>
    a.IndexData.All(b =>
        b.DataField.All(c =>
            _index.Index.Where(z =>
                z.IndexData.All(y => y.DataField.Contains(c.name))
            )
        )
    )
);

Upvotes: 16

Views: 26384

Answers (1)

vcsjones
vcsjones

Reputation: 141638

Except is a good way of doing that:

var items = source1.Except(source2);

Would return all items in source1 except those in source2.

Since your collections appear to be different types, you would do something like:

source1.Except(source2.Select(s => /* selector here */))

Or you could create your own implementation of IEqualityComparer and use that to compare the two different types.

Upvotes: 48

Related Questions