如何将 ELSE 部分转换为单个 Lambda 或 LINQ 查询。
我想去掉多个 for/foreach 语句。我通过多种方式尝试过它,但 lamda 查询没有给我想要的结果。
例如:如果 response.UResources 没有数据(即它的空列表)
这里CurrentBS是List,UResources是List
List<BSS> noTask = new List<BSS>();
if (response.CurrentBS.Count > 0 &&
response.UResources != null &&
response.UResources.Count == 0)
{
noTask = response.CurrentBS.Where(x => x.CurrentBS.TaskId == 0).ToList();
}
else
{
var bnt = response.CurrentBS.Where(x => x.CurrentBS.TaskId == 0).ToList();
for (int index = bnt.Count() - 1; index >= 0; index--)
{
foreach (var uResource in response.UResources)
{
if (bnt[index].BotId.ToString().ToLower() == uResource.Name.ToLower()
&& uResource.Type == ResourceType.Bot)
{
bnt.RemoveAt(index);
}
}
}
noTask = bnt;
}
非常简单,只需在整个条件周围放置一个
!
并将其推入.Where
。你也可以结合if
的两侧。
还请注意,您应该进行不区分大小写的比较,而不是使用
ToLower
。
var results = response.CurrentBS.Where(x => x.CurrentBS.TaskId == 0);
if (!(response.CurrentBS.Count > 0 &&
response.UResources != null &&
response.UResources.Count == 0))
{
results = results.Where(b =>
!(string.Equals(b.BotId.ToString(), uResource.Name, StringComparison.OrdinalIgnoreCase)
&& uResource.Type == ResourceType.Bot));
}
var noTask = results.ToList();
看来你总是初始化列表
List<BSS> items = response.CurrentBS.Where(x => x.CurrentBS.TaskId == 0).ToList();
现在您只需要找出要删除的项目:
if(response.UResources?.Any() == true)
{
items.RemoveAll(CheckIfRemove);
}
bool CheckIfRemove(Bss btn)
{
return response.UResources
.Any(r => StringComparer.OrdinalIgnoreCase.Equals(r?.Name, btn.BotId.ToString()));
}