Convert nested for-loops into single LINQ statement(将嵌套的 for 循环转换为单个 LINQ 语句)
问题描述
有人可以帮我把这个嵌套结构变成一个 LINQ 语句吗?
can someone please help me turn this nested structure into a single LINQ statement?
EventLog[] logs = EventLog.GetEventLogs();
for (int i = 0; i < logs.Length; i++)
{
if (logs[i].LogDisplayName.Equals("AAA"))
{
for (int j = 0; j < logs[i].Entries.Count; j++)
{
if (logs[i].Entries[j].Source.Equals("BBB"))
{
remoteAccessLogs.Add(logs[i].Entries[j]);
}
}
}
}
推荐答案
嵌套循环通常以多个from"子句结束(编译器将其转换为对 SelectMany
的调用):
Nested loops usually end up with multiple "from" clauses (which are converted into calls to SelectMany
by the compiler):
var remoteAccessLogs = from log in EventLogs.GetEventLogs()
where log.LogDisplayName == "AAA"
from entry in log.Entries
where entry.Source == "BBB"
select entry;
(假设 remoteAccessLogs
在此调用之前为空,并且您很乐意直接对其进行迭代 - 如果您想要 ToList()
代码>列表<T>.)
(That's assuming that remoteAccessLogs
is empty before this call, and that you're happy iterating over it directly - you can call ToList()
if you want a List<T>
.)
这是点符号的形式:
var remoteAccessLogs = EventLogs.GetEventLogs()
.Where(log => log.LogDisplayName == "AAA")
.SelectMany(log => log.Entries)
.Where(entry => entry.Source == "BBB");
或者列表:
var remoteAccessLogs = EventLogs.GetEventLogs()
.Where(log => log.LogDisplayName == "AAA")
.SelectMany(log => log.Entries)
.Where(entry => entry.Source == "BBB")
.ToList();
请注意,我使用重载的 == 表示字符串,因为我发现它比调用 Equals
方法更容易阅读.两者都可以.
Note that I've used the overloaded == for string as I find it easier to read than calling the Equals
method. Either will work though.
这篇关于将嵌套的 for 循环转换为单个 LINQ 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将嵌套的 for 循环转换为单个 LINQ 语句


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01