1

Trying to remove a particular error from c# ModelState using linq but not successful..

Linq not working/removing items but no error:

 ModelState.Values.ToList().ForEach(u =>
            {
                if (u.Errors.Any())
                {
                    u.Errors.ToList().RemoveAll(z =>
                        z.ErrorMessage == "Exceeded allowed chars");
                }
            });

Working one:

foreach (var s in ModelState.Values)
            {
                foreach (var e in s.Errors.ToList())
                {
                    if (e.ErrorMessage == "Exceeded allowed chars")
                        s.Errors.Remove(e);
                }
            }

Why the above linq not removing error item? what I'm missing? Possible to avoid ToList() in linq to avoid performance penalty?

Error while assigning errors to modelstate

  • why `.ToList()`. Remove that then it should work. `ToList` creates a new list – user1672994 Jun 05 '21 at 08:17
  • without .ToList() it is IEnumerable type & you cant call RemoveAll() – Zackie Khan Jun 05 '21 at 08:24
  • Does this answer your question? [Remove ModelState errors in ASP.NET MVC](https://stackoverflow.com/questions/36361095/remove-modelstate-errors-in-asp-net-mvc) – Selim Yildiz Jun 05 '21 at 08:29
  • my requirement is different, dont want to remove a particular control/property related error always. But dynamically want to remove errors if it message equals "Exceeded allowed chars" for example. – Zackie Khan Jun 05 '21 at 08:35
  • @AlirezaAhmadi, not the one I'm looking for. I have the solution & posted the same above. But want to know the mistake I have done in my LINQ above – Zackie Khan Jun 05 '21 at 08:45

0 Answers0