dimanche 12 janvier 2020

Finding index of an element in a List

I am creating some List<T> lists which I save into a List<FieldInfo> ListOfFields using a reflection method (why, doesn't matter right now and I am here showing only the affected code):

List<FieldInfo> ListOfFields = new List<FieldInfo>();

foreach (FieldInfo field in this.GetType().GetFields())
{
   ListOfFields.Add(field); // saves all my List<T> in the ListOfFields list
}

Every field of the foreach loop will be of the same type List<T>.
I am trying to find out a method where to pass a <T> obj> and loop through every field (List<T>) untill I find the match obj == field[i], something like for example:

public Tuple<string, string> GetElementTupleFor<T>(T obj)
{
    foreach(FieldInfo field in ListOfFields)
    {
       var elements = field.MyRequestForA_GetElements_Method(); // does such method exist?
       for(int i=0; i<elements.Count; i++)
       {
          if (obj == elements[i])
          {
             return new Tuple<string, string>(field.Name, ""+i);
          }
       }
    }
    return new Tuple<string, string>("NotFound", "?");
 }

Thanks in advance for any help!





Aucun commentaire:

Enregistrer un commentaire