[英]Need help in Linq
I am writing a Linq query just for learning. 我在写Linq查询只是为了学习。
var result = Process.GetProcesses()
.Where(p => p.WorkingSet64 > 20 * 1024 * 1024)
.OrderByDescending(p => p.WorkingSet64)
.Select(p => new {p.Id,p.ProcessName,p.WorkingSet64 });
I want to iterate in to result 我想在迭代导致
foreach(process in result) //error-type or namespace process could not be found.
{
Console.WriteLine(Process.ProcessName);
}
I want to iterate in to result and print each process name on the console. 我想遍历结果并在控制台上打印每个进程名称。
What I am doing wrong. 我做错了。
you're close: 您接近:
foreach (var process in result) {
Console.WriteLine(process.ProcessName);
}
(I'm assuming you haven't declared the name process
before.) (我假设您之前没有声明过名称process
。)
Also note that if you use process (with a small p) in the foreach line, you need to keep the same case when you use it inside the loop. 还要注意,如果在foreach行中使用process(带有小p),则在循环内使用它时,需要保持相同的大小写。
Are you declared process
before loop? 您是否在循环之前声明了process
? If not you should change your for each
to 如果不是,则应将for each
更改for each
foreach(var process in result)
{
Console.WriteLine(process.ProcessName);
}
Consider using LINQ's query syntax for terser code: 考虑对更短的代码使用LINQ的查询语法:
var result = from p in Process.GetProcesses()
where p.WorkingSet64 > 20 * 1024 * 1024
orderby p.WorkingSet64 descending
select new { p.Id, p.ProcessName, p.WorkingSet64 };
Then, instead of a loop, think in LINQ to do the same thing: 然后,而不是循环,在LINQ中考虑做同样的事情:
Console.WriteLine(string.Join("\r\n", result.Select(p => p.ProcessName)));
EDIT: The overload of string.Join() used above was only introduced in .NET 4.0. 编辑:上面使用的string.Join()重载仅在.NET 4.0中引入。 To use an overload that is available in earlier versions, which accepts a string[]
rather than an IEnumerable<string>
, just chain a .ToArray()
after the .Select()
: 要使用早期版本中可用的重载,该重载接受string[]
而不是IEnumerable<string>
,只需在.Select()
之后链接.ToArray()
.Select()
:
Console.WriteLine(string.Join("\r\n", result.Select(p => p.ProcessName).ToArray()));
You could also project your query into a list of processes: 您还可以将查询投影到进程列表中:
List<Process> result = Process.GetProcesses()
.Where(p => p.WorkingSet64 > 20 * 1024 * 1024)
.OrderByDescending(p => p.WorkingSet64).ToList();
foreach(Process process in result)
{
Console.WriteLine(process.ProcessName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.