3

有什么办法可以将以下代码简化为 Linq 形式?

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

我能想到的只有:

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比嵌套的 foreach 循环更具可读性,并且需要更少的代码。所以这就是我想要它的原因LINQ

4

3 回答 3

2
var deleteList = currentWhiteListApps.Where(x =>
                     clientSideWhiteLists.All(y => !x.appID.Equals(y.appID)))
                                     .ToList();
于 2013-03-25T11:42:06.663 回答
1
var deleteList = currentWhiteListApps.Except(clientSideWhiteLists).ToList();

此解决方案假定两个集合都包含相同类型的元素,并且此类型已覆盖比较 appID 的 Equals()。

于 2013-03-25T11:43:24.123 回答
0
var validIds = new HashSet<int>(clientSideWhiteLists.Select(x => x.appId));
var deleteList = currentWhiteListApps.Where(x => !validIds.Contains(x.appId)).ToList();
于 2013-03-25T13:41:25.430 回答