kosnkov
kosnkov

Reputation: 5941

Cannot convert from 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.Generic.IEnumerable<int?>'

class first
{
    private int? firstID;
}

class second
{
    private int secondID;
    private int secondField;
}

public override Expression<Func<first, bool>> FirstFilter()
{
    Contex db = new Contex();
    List<second> list = (from p in db.second select p).ToList();

    return b => list.Select(p => p.secondID).Contains(b.firstID);
}

and I have error:

cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'

I have tried many different ways, but I just don't know how can I fix it.

Upvotes: 0

Views: 4640

Answers (2)

driis
driis

Reputation: 164341

Use this:

list.Select(p => p.secondID).Cast<int?>().Contains(b.firstID);

You are getting the problem, because list.Select(p => p.secondID) will be an IEnumerable<int?, but because firstID is int (non-nullable), overload resolution cannot determine a valid overload of Contains to call. You cannot implicitly convert from IEnumerable<int?> to IEnumerable<int>. The Cast extension method works by casting each element to int.

As mentioned in another answer, you could also simply pass in a non-nullable int into Contains:

list.Select(p => p.secondID).Contains(b.firstID ?? 0);

But, do be aware that this might not be want. If the first list contains 0, and firstID is null, the result will be true, because you pass in 0 when the value is null.The Cast version of the expression returns false when firstID is null.

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

Try providing a default value for firstID if it is null:

return b => list.Select(p => p.secondID).Contains(b.firstID ?? 0);

Upvotes: 0

Related Questions