Reputation: 7986
Consider the following code:
private static void WriteProcesses(StreamWriter sw, DateTime d) {
sw.WriteLine("List of processes @ " + d.ToString());
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
if(localAll.Length > 0) {
for(int i = 0; i < localAll.Length; i++) {
sw.WriteLine(" " + localAll[i].ProcessName);
}
}
}
But i get a red squiggly line saying:
Cannot implicitly convert type System.Collections.Generic.IEnumerable' to 'System.Diagnostics.Process[]'. An explicit conversion exists (are you missing a cast?)
I tried changing the array to a List but didnt work.
Upvotes: 0
Views: 882
Reputation: 32698
I would rewrite your code like this:
private static void WriteProcesses(StreamWriter sw, DateTime d) {
sw.WriteLine("List of processes @ " + d.ToString());
var localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
foreach(var local in localAll) {
sw.WriteLine(" " + local.ProcessName);
}
}
Your problem is coming from the fact that Where
returns an IEnumerable
which cannot be mapped to an array. But there is no need for you to use an array so I've taken the use of it out. The length
check is just making the code less clear for me so I changed to a foreach
as well.
Upvotes: 1
Reputation: 241611
Change
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
to
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost").ToArray();
Where
is returning an IEnumerable<Process>
on which you can call ToArray
to convert to an array of type Process
.
Alternatively, you can enumerate through the IEnumerable<Process>
that Where
returns.
var processes = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
foreach (Process process in processes) {
sw.WriteLine(" " + process.ProcessName);
}
Upvotes: 5
Reputation: 532435
I think you'd be better off to just deal with it as an IEnumerable
private static void WriteProcesses(StreamWriter sw, DateTime d) {
sw.WriteLine("List of processes @ " + d.ToString());
var localAll = Process.GetProcesses()
.Where(o => o.ProcessName.ToLower() != "svchost");
foreach(Process process in localAll) {
sw.WriteLine(" " + process.ProcessName);
}
}
Upvotes: 2
Reputation: 146
The .Where method returns an IEnumerable, where T is the type being filtered. For this example you would need to call .ToArray( ) after the Where to convert the collection to an array.
Upvotes: 0
Reputation: 78104
If you don't want to use ToArray(), change Process[] to var then hover over it to see what type is being returned from the Where statement. (Or just hover over the Where() method, which will tell you the same thing)
Upvotes: 0