0

I have a class that I created below

 public class Program_TFT
{     
    public string ProgramName;
    public int NumberOfProjects;
    public List<Project> Projects = new List<Project>();        
}

and I created a list with this class

public static List<Program_TFT> Programs = new List<Program_TFT>();

I need to be able to call elements of lists with string indexer instead of integer. Like this it works

 Programs[Programs.FindIndex(x => x.ProgramName == "Prog_1")]

But instead of that I want to create a direct string indexer like this

 Programs["Prog_1"]

What can I do? Thanks

Cem
  • 1
  • 3
    I'd change your list in the a dictionary with a string key. – Kevin Smith May 22 '21 at 09:59
  • 1
    Instead of `Programs[Programs.FindIndex()]]`, you could use `Programs.Single(p => p.Name == "Prog_1")`. But yeah, you might want to consider using a dictionary as Kevin suggested. Alternatively, you could write your own class which [extends](https://stackoverflow.com/q/21692193/8967612) `List`. – 41686d6564 stands w. Palestine May 22 '21 at 10:00
  • This seems to be the solution at this moment, will need to change lots of code though, I was wondering if there would be another way to do it. Thank you Kevin Smith – Cem May 22 '21 at 10:02
  • I will try the solution Kevin has suggested. Thank you 41686d6564 – Cem May 22 '21 at 10:05
  • Does this answer your question? [C# collection indexed by property?](https://stackoverflow.com/questions/17538191/c-sharp-collection-indexed-by-property) and [How to write a class that (like array) can be indexed with `arr[key]`?](https://stackoverflow.com/questions/6807310/how-to-write-a-class-that-like-array-can-be-indexed-with-arrkey) –  May 22 '21 at 10:19

2 Answers2

0

Instead of creating a list of programs:

public static List<Program_TFT> Programs = new List<Program_TFT>();

Create a dictionary of programs where the key is the ProgramName:

public static Dictionary<string, Program_TFT> Programs = new Dictionary<string, Program_TFT>();

If you already have the list of programs somewhere, you can convert it directly into a dictionary by using .ToDictionary:

Dictionary<string, Program_TFT> Programs = list.ToDictionary(x=>x.ProgramName);
Neil
  • 11,059
  • 3
  • 31
  • 56
-1

You can use a Dictionary<string, Program_TFT> as the other answer suggested, or do this

Programs.SingleOrDefault(x => x.ProgramName == "Prog_1")

Line above assumes there will be a maximum of one program with the name, it will throw an error if more than one, or returns null if there isn't any. You will need to manage duplications yourself.

Mocas
  • 1,403
  • 13
  • 20