有没有办法将以下代码缩减为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;
});
LINQ的原因
LINQ
比嵌套的foreach循环更具可读性,并且需要的代码更少。所以这就是我希望LINQ
答案 0 :(得分:2)
var deleteList = currentWhiteListApps.Where(x =>
clientSideWhiteLists.All(y => !x.appID.Equals(y.appID)))
.ToList();
答案 1 :(得分:1)
var deleteList = currentWhiteListApps.Except(clientSideWhiteLists).ToList();
此解决方案假定两个集合都包含相同类型的元素,并且此类型已覆盖比较appID的Equals()。
答案 2 :(得分:0)
var validIds = new HashSet<int>(clientSideWhiteLists.Select(x => x.appId));
var deleteList = currentWhiteListApps.Where(x => !validIds.Contains(x.appId)).ToList();