Doubt filter with Line, ASP NET MVC

Asked

Viewed 163 times

2

I have a question on a filter using Linq, I have a critical object Inside criticism has a ienumerable I need to return a list of criticisms that the status of the last critical move equals 2 But the code below is giving error

var Criticas = from a in Db.Criticas select a; 
Criticas = Criticas.Where(c => c.MovimentacoesCritica.LastOrDefault().Status.Equals(2));
  • read twenty times and did not understand its doubt! D

  • You said you were having a doubt, showed a little code and gave a basic explanation of what you’re trying to do. But in the end, you didn’t say what the doubt is after all!

  • Do you want to get the last record with the status equal to 2? It’s very confusing.

  • You are very confused... You want to get the last item in the list when it has status equal to 2? or you want to get the last one in the list that is status 2?

1 answer

2


I simulated your code in Linqpad with Lists and Enumerable and it worked correctly, probably the problem is because your query (var Criticas = from a in Db.Criticas select a;)returns a Iqueryable object and when calling Where it fails to process Lastordefault for a new Iqueryable.

Try to convert Criticas to List or Enumerable

var Criticas = (from a in Db.Criticas select a).ToList();
    var ListCriticas = Criticas.Where(c => c.MovimentacoesCritica.LastOrDefault(o => o.Status.Equals(2)) != null);
  • gives the following error: An Exception of type 'System.Argumentnullexception' occurred in System.Core.dll but was not handled in user code Additional information: Value cannot be null.

  • 1

    The correct thing would be: c.MovimentacoesCritica.LastOrDefault(e => e.Status.Equals(2))

  • @Kleberbarros, it must be that Lastordefault is returning null because it has no item in the list. Lastordefault generates this null when there are no items in the list.

  • @Filipeoliveira, actually, I will edit the answer, it will even solve the empty list question that Kleber commented. vlw

  • Continue giving Argumentnullexception

  • @Kleberbarros The Status field accepts null values? it may be that some item in the list is with the null property and in this case the . Equals throws exception try to change the condition to (o => o.Status != null && o.Status.Equals(2))

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.