Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing elements from a List which respect a condition on the index

I’m asked to create a function which removes all the elements from a list of integers respecting a specified condition i.e. the element is multiple of his index.

It is very easy to do it with iterations and things like that but I wanted to do it in a "cuter" way just to get into more complex writing codes, Linq and Lambdas.

That’s what I’ve tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public static List<int> MultipleOfIndex(List<int> xs) =>
    xs.RemoveAll(s => (s % xs.IndexOf(s) == 0));

but I get the following error: error CS0029: Cannot implicitly convert type ‘int’ to ‘System.Collections.Generic.List’

I can’t really understand where I’m doing an implicit conversion since my logic is this: I want to remove all the elements s where s modulo his index is 0.
I’d like to have an explanation and also I’d like to see how can I also implement it with Where/Select clauses.

Thanks in advance!

>Solution :

If you want to modify the original list, you can use the following (note that you need to handle a divide-by-zero)

public static List<int> MultipleOfIndex(List<int> xs)
{
    xs.RemoveAll(s => xs.IndexOf(s) != 0 && s % xs.IndexOf(s) == 0);
    return xs;
}

A more efficient version might be:

public static List<int> MultipleOfIndex(List<int> xs)
{
    for (var i = xs.Count - 1; i > 0; i--)
    {
        if(xs[i] % i == 0)
            xs.RemoveAt(i);
    }
    return xs;
}

If you want to create a new list, you can use LINQ

public static List<int> MultipleOfIndex(List<int> xs) =>
    xs.Where((s, index) => index == 0 || s % index != 0).ToList();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading