I'm having to go through a big solution that contains unavailable projects. These unavailable projects are unavailable because their paths don't exist anymore. If this solution were to keep these unavailable references, would there be a way to determine if each project I am looping on is available/unavailable?
Below is a loop whose goal is to determine if every ProjectItem within the current solution is saved. But, since certain projects are unavailable, I keep getting null references.
bool isDirty = false;
foreach (Project proj in sln.Projects) //sln is my current solution
{
if (proj == null) //hoping that might do the trick
continue;
foreach (ProjectItem pi in proj.ProjectItems)
{
if (pi == null) //hoping that might do the trick
continue;
if (!pi.Saved)
{
isDirty = true;
break;
}
}
}
You can rewrite this in a simple LINQ
operation:
//import the LINQ extensions
using System.Linq;
// some code here;
bool isDirty = sln.Projects.Any(pr => pr.ProjectItems != null && !pr.Saved);
According to the MSDN, the _Solution.Projects
property is a Projects
typed, which is a IEnumerable
without generic, so you should use the OfType<TResult>
extension method, like this:
bool isDirty = sln.Projects.OfType<Project>().Any(pr => pr.ProjectItems != null && !pr.Saved);
From MSDN:
This method is one of the few standard query operator methods that can be applied to a collection that has a non-parameterized type, such as an
ArrayList
. This is becauseOfType<TResult>
extends the typeIEnumerable
.OfType<TResult>
cannot only be applied to collections that are based on the parameterizedIEnumerable<T>
type, but collections that are based on the non-parameterizedIEnumerable
type also.