Kurkula
Kurkula

Reputation: 6762

Linq compare 2 string arrays when both have same values

I have 2 string arrays/values x,y and am trying to get values of y which are not in x. I am trying to get this value only in case if all values of x are also in y.

        string x = "CA ,WA";
        string y = "CA,WA,NY";
        var srcDetails = x.ToLower().Replace(" ", string.Empty).Split(',');
        var dstDetails = y.ToLower().Replace(" ", string.Empty).Split(',');

        var common = dstDetails.Intersect(srcDetails); //common in x,y

        var destGreaterSrc= dstDetails.Except(srcDetails); //if y > x

        var extraInDest = dstDetails.Except(common); 

extraInDest is extra value in y which is not in x

In above code extra values in dest which is outputted as NY.

I am trying to find the scenario where values of x may not be equal to y like

    string x = "CA ,NV";
    string y = "CA,WA,NY";

how can we make var extraInDest output to false.

like var extraInDest = dstDetails.Except(common) resulting false or null

Upvotes: 0

Views: 101

Answers (2)

Owuor
Owuor

Reputation: 616

This should be simple, if your comparison should always result in a boolean value, you should use this instead

bool extraInDest = srcDetails.All(v=>dstDetails.Contains(v));

Upvotes: 1

grafgenerator
grafgenerator

Reputation: 818

The simpliest one would be

var extraInDest = srcDetails.Except(dstDetails).Any()
    ? null 
    : dstDetails.Except(srcDetails);

Upvotes: 1

Related Questions