How to how to get the indexes of all occurrences of a string in a list using Linq with C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Collections.Generic;
   
class Program
{
    static void Main() {
        var list = new List<string> { "c++", "c-sharp", "c", "c++", "java", "php", "c++" };
   
        int[] indexes = list.Select((s, i) => s == "c++" ? i : -1).Where(i => i != -1).ToArray();
        
        Console.WriteLine(string.Join(", ", indexes));
    }
}
   
   
   
   
/*
run:
      
0, 3, 6
    
*/

 



answered Jul 6, 2023 by avibootz
...