1

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.

S2S2
  • 8,322
  • 5
  • 37
  • 65
Nicholas N
  • 205
  • 1
  • 4
  • 8
  • 1
    "assuming each value of var1 is unique, would it be simply faster if I use a Dictionary with var1 as the key instead" Don't know for sure about faster, but it'd definitely be much more straightforward. – BoltClock Nov 10 '11 at 16:50
  • Why are you looking for the index? Are you looking to sort it or something, or just retrieve it? – Daryl Nov 10 '11 at 16:54
  • Retrieving it. I could do the same using Dictionary and using var1 as the key, but was wondering if I could avoid building a dictionary for each list I have. – Nicholas N Nov 10 '11 at 17:01

5 Answers5

3
int index = myList.FindIndex(x => x.var1 == 20);
Stecya
  • 22,896
  • 10
  • 72
  • 102
2

faster is a very relative term. It always depends on the number of objects in your collection. It would probably be easier and make more sense though.

Using your example:

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"});

var dict = myList.ToDictionary(k => k.var1);
exampleClass item1 = dict[20];
Daryl
  • 18,592
  • 9
  • 78
  • 145
2
var index = myList.FindIndex(val => val.Var1 == 20);
S2S2
  • 8,322
  • 5
  • 37
  • 65
1

Here is a full article on doing just that. It offers up several solutions depending on your need.

arb
  • 7,753
  • 7
  • 31
  • 66
  • wow, thanks for the link. Some of the stuff in there is beyond my rudimentary C# understanding, but it gave me pointers for further research. – Nicholas N Nov 10 '11 at 17:10
1

You can use the Find method to retrieve the object (or FindAll to retrieve all objects):

myList.Find(x => x.var1 == 20);

Or the FindIndex to retrieve its index in the List:

myList.FindIndex(x => x.var1 == 20);
Otiel
  • 18,404
  • 16
  • 78
  • 126