- Home /
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?
Answer by ShadyProductions · Jun 15, 2020 at 06:56 PM
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]
Or
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)
{
position++;
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:
https://docs.microsoft.com/en-us/dotnet/api/system.object.gethashcode?view=netcore-3.1
Hi thanks for the answer,
The issue is that I don't always know which element is where in the list because they can be moved by the player.
It's an inventory system.
Say we have axe in slot 1, nothing in slots 2-9.
If the player drops the axe into slot 9 it will ins$$anonymous$$d get dropped into slot 2 because i use a blank "Nothing" item to fill empty slots in the list.
Video to help try and explain. https://www.youtube.com/watch?v=_AonRL0stp4&feature=youtu.be
Actually ins$$anonymous$$d of using the default "Nothing" item, if i Item i = new Item(); and then add I to the list they are technically unique and it doesn't cause this issue.
Thanks for the assistance.
Why not set the inventory slots you don't use to null?