E
E
embiid2021-01-30 11:10:57
LINQ
embiid, 2021-01-30 11:10:57

How to find duplicate elements in a list?

For example, there is a list like this:

List<int> numbers = new List<int>{5, 3, 5, 9, 7, 8, 22, 5};


You need to find the index of the elements where the values ​​= 5 and display them

. That's the only thing I could do, display only the 1st element 5.
int indx = numbers.FindIndex(item => item == 5);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
ayazer, 2021-01-30
@embiid

judging by the description and tags, the question is still "how to find the indices of repeated elements using linq"

var lst = new List<int>() { 1, 2, 3, 5, 1, 6, 5 };

            var result = lst.Select((el, idx) => (el, idx))
                .GroupBy(c => c.el)
                .Where(g => g.Count() > 1)
                .SelectMany(g => g.Select(c => c.idx).ToList())
                .ToList();  // [0, 4, 3, 6]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question