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
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();