Search code examples
c#listgeneric-collections

C#: finding class fields in a List


I have the following code:

class exampleClass
{
    int var1;
    int var2;
    string var3
}

List<exampleClass> myList = new List<exampleClass>()

myList.Add(new exampleClass { var1 = 10, var2 = 100, var3 = "a"});
myList.Add(new exampleClass { var1 = 20, var2 = 200, var3 = "b"});
etc.

If I would like to find the index # of the object in the List where var1 = 20, how do I go about doing that (in this case, var1 = 20 is in myList[1])?

I tried using Contain() but came up with errors.

And on a related subject, assuming each value of var1 is unique, would it be simply faster if I use a Dictionary with var1 as the key instead. Thanks.


Solution

  • int index = myList.FindIndex(x => x.var1 == 20);