How to make an in in lambda?

1

I have a function convertStringListaInt with parameter String .

Example:

String: 1,2 .

I'm converting this string to a List of type convertStringListaInt_Result having property number (integer).

How can I make a in using Lambda ?

I noticed Entity accepts only primitive types in the comparison and that is why the error is generated.

Code:

public static bool ExisteAIPR(string IDEscopo) {
       using(entidadesIUS entidades = new entidadesIUS()) {
       List <convertStringListaInt_Result> resultado = entidades.convertStringListaInt(IDEscopo).ToList();
       return entidades.Escopos.Where(e => resultado.Select(x => x.number).Contains(e.IDEscopo) && e.AIPR == "S").FirstOrDefault() != null ? true : false;
   }
}

Generated Error

  An exception of type 'System.NotSupportedException' occurred in   EntityFramework.SqlServer.dll but was not handled in user code

     

Additional information: Unable to create a constant value of type   'Template.DTO.convertStringListaInt_Result'. Only primitive types or   enumeration types are supported in this context.

    
asked by anonymous 03.11.2014 / 13:59

1 answer

2

From the question, I'm guessing convertStringListaInt_Result should look something like this:

public class convertStringListaInt_Result 
{
    ...
    public int number { get; set; }
    ...
}

The logic is almost right, but using .Select(x => x.number) you are returning an integer, and the idea is to return a list of integers. Contains is operated on top of a list, not on top of each element.

In this case, you would have to use ToList , not just Select . Select returns a generating function of the type of element placed in the predicate, not the list itself. It would look something like this:

    public static bool ExisteAIPR(string IDEscopo)
    {
        using (entidadesIUS entidades = new entidadesIUS())
        {
            List<int> resultado = entidades.convertStringListaInt(IDEscopo).Select(x=> x.number).ToList(); 
            return entidades.Escopos.Where(e => resultado.Contains(e.IDEscopo) 
&& e.AIPR == "S").FirstOrDefault() != null;
        }
    }

Or, taking advantage of the first version of the answer, you can modify the convertStringListaInt method to return a list of integers:

 public static bool ExisteAIPR(string IDEscopo)
    {
        using (entidadesIUS entidades = new entidadesIUS())
        {
            List<int> resultado = entidades.convertStringListaInt(IDEscopo).ToList();
            return entidades.Escopos.Where(e => resultado.Contains(e.IDEscopo) && e.AIPR == "S").FirstOrDefault() != null;
        }
    }
    
27.11.2014 / 23:08