1

The method Solution.Projects.Index(Object index) get an index of project as number.

I have the name of the project. How can I determine the index in the solution of this project programmatically?

user3114639
  • 1,895
  • 16
  • 42
  • It appears that you need to test Projects names in loop like in (MSDN)[http://msdn.microsoft.com/en-us/library/EnvDTE.Projects.aspx] (can't test from phone) – PTwr Jan 02 '14 at 08:36

2 Answers2

6

You can use linq:

string yourProject = "ProjectName";
var query = Solution.Projects.Cast<Project>()
            .Select((p, i) => new { Name = p.Name, Index = i})
            .First(p => p.Name == yourProject).Index;
w.b
  • 11,026
  • 5
  • 30
  • 49
  • OP asked, how he could find "the index in the solution of this project", not the project itself, or am I missing something? – Yurii Jan 02 '14 at 08:50
  • This code cause to the following error: 'EnvDTE.Projects' does not contain a definition for 'Cast' and no extension method 'Cast' accepting a first argument of type 'EnvDTE.Projects' could be found (are you missing a using directive or an assembly reference?) – user3114639 Jan 02 '14 at 09:35
  • add `using System.Linq`, this is an extension method from `System.Linq.Enumerable` – w.b Jan 02 '14 at 09:57
  • The indexes of the projects start from 1, and this code return from 0, how should I change it to return the correct index? – user3114639 Jan 02 '14 at 10:16
  • Indexes in all collections start from 0, if you want you can add 1 to the result. – w.b Jan 02 '14 at 10:22
1

If you have the name of the project, you could loop through all the projects to find the index of the desired project:

int index = 0;
foreach(Project project in dte.Solution.Projects)
{
    if (string.Equals(project.Name, "desired project name"))
    {
        break;
    }
    index++;
}

On the other hand why do you actually need the index of the project? You can use Item method with project name as parameter as well.

The value passed to index is an integer that is an index to a Project object in its collection. The value of index can alternatively be a string value that equates to the name of a project in the collection.

Yurii
  • 4,811
  • 7
  • 32
  • 41