Callum Linington
Callum Linington

Reputation: 14417

Reduce 2 foreach loops into a linq query

Is there any way to reduce the following code into Linq form?

foreach (var current in currentWhiteListApps)
{
    var exists = false;

    foreach (var whiteList in clientSideWhiteLists)
    {
       if (current.appID.Equals(whiteList.appID))
       {
           exists = true;
       }
    }
    if (!exists)
    {
        deleteList.Add(current);
    }
}

All I can think of is:

currentWhiteListApps.Select(x => {
    var any = clientSideWhiteLists.Where(y => y.appID.Equals(x.appID));
    if (any.Any())
        deleteList.AddRange(any.ToArray());
    return x;
});

Reason For LINQ
LINQ is far more readable than nested foreach loops, and requires less code. So this is the reason I would like it in LINQ

Upvotes: 3

Views: 2000

Answers (3)

Firo
Firo

Reputation: 30813

var validIds = new HashSet<int>(clientSideWhiteLists.Select(x => x.appId));
var deleteList = currentWhiteListApps.Where(x => !validIds.Contains(x.appId)).ToList();

Upvotes: 0

alex
alex

Reputation: 12654

var deleteList = currentWhiteListApps.Except(clientSideWhiteLists).ToList();

This solution assumes that both collections contains elements of the same type and this type has overriden Equals() that compares appID.

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

var deleteList = currentWhiteListApps.Where(x =>
                     clientSideWhiteLists.All(y => !x.appID.Equals(y.appID)))
                                     .ToList();

Upvotes: 2

Related Questions