C
C#2y ago
Sam DZ

✅ how to know the index of repeated items in list ?

I have an list with repeated values i want to know the index of this values ! P.S i will not delete this repeated values
14 Replies
Thinker
Thinker2y ago
A simple approach would be something like this
static void List<int> GetIndicies<T>(List<T> items, T value)
{
List<int> indicies = new();

for (int i = 0; i < items.Count; i++)
{
if (items[i].Equals(value)) indicies.Add(i);
}

return indicies;
}
static void List<int> GetIndicies<T>(List<T> items, T value)
{
List<int> indicies = new();

for (int i = 0; i < items.Count; i++)
{
if (items[i].Equals(value)) indicies.Add(i);
}

return indicies;
}
Sam DZ
Sam DZOP2y ago
@Diddy yes and i will take that index to print them When i use loop and compare with the value they stuck at first item @🌈 Thinker 🌈 I'm not understanding the code !
Thinker
Thinker2y ago
It creates a generic static method GetIndicies which takes a generic list and a value, then it loops through each of the items in the list. If the item at the current index is equal to the item which was passed into the method, then it adds the index to a list. Finally it returns the list of indicies. If you haven't encountered generic methods (<T>) before, then I'd suggest reading up on generics.
Nora
Nora2y ago
List<int> indicies = new();
List<int> indicies = new();
Wow, I didn't know we could write it this way
Thinker
Thinker2y ago
It's the same thing as List<int> indicies = new List<int>();, just shorter. Alternatively you can write var indicies = new List<int>();
Nora
Nora2y ago
Is it a good practice?
Thinker
Thinker2y ago
Makes your code shorter
Nora
Nora2y ago
Seems like it would save some efforts editing the names/types when you need a change Thanks!
Sam DZ
Sam DZOP2y ago
Can i use .IndexOf(,) ? With loop @🌈 Thinker 🌈 It work ! Lol @🌈 Thinker 🌈 But give me out of range ! I will capture it to see how we can solve it
Sam DZ
Sam DZOP2y ago
Thinker
Thinker2y ago
Since you're setting index to ddate.IndexOf(d, x), then the likely thing is that ddate does not contains the value d, and therefore index is set to -1, which causes the exception.
Sam DZ
Sam DZOP2y ago
I put them inside try & catch And worked fine ! Lol Thank you @🌈 Thinker 🌈
Thinker
Thinker2y ago
That's just ignoring the issue but sure
Sam DZ
Sam DZOP2y ago
Yes exactly that what i do lol The deadline is today and I don't have time to fix it
Want results from more Discord servers?
Add your server