Find specific element when duplicates exist in list.

How do you get an element from a list when there are duplicates of that element in the list?

Take the following list for example.

A, B, C, C, C, D

IndexOf will always return the C in element 2, but what if I want C in element 4?

So the way I’m taking your question is that you are comparing some default value type of c#
that don’t have a hashcode comparison like objects do

Say you have an array of integers:

var arr = new int [] {1,1,2,3,5,6,6,7,7,7,9};

And you want to find nr 7 on index 8

There are a few ways:

You already know that there is a 7 on index 8 and access it directly arr[8]


Loop the array and count up the 7’s until you reach the 2nd one:

int position = 0;
foreach (var nr in arr)
    if (nr == 7)
        if (position == 2)
            return nr;

Your question would make a lot more sense if you had an object that you can uniquely identify
with some kind of an Id, or hash.

public class Book
    public string Author;
    public string Title;

An example:

public Book[] Books = new Book[2];
var exampleBook = new Book { Author = "Idk", Title "Example" };
Books[0] = new Book { Author = "Me", Title = "Also me" };
Books[1] = exampleBook;

var index = Books.IndexOf(exampleBook);

IndexOf here will return the correct index 1, because it compares the hashcode of the two object and
they are the same.
You can override this behaviour, by overriding the Equals method.

You can read about it here: