While building a ASP.NET-MVC website I was trying to implement a EDIT page on my website, but I'm having some difficulties, particulary in my Controller. The error is in this class, pointing to the ID:
According to List<T>.Contains(T)
, you need parse T
object which is GestaoAlertas
object to your addresses
(List<GestaoAlertas>
type).
Hence, you get the error below as it is an unmatched type with int
It is not possible to convert from int to "hdsportal.GestaoAlertas"
for this line:
GestaoAlertas _teste = addresses.Contains(ID);
And List<T>.Contains(T)
returns the boolean result.
public bool Contains (T item);
Determines whether an element is in the List.
Assumptions:
addresses
contain GestaoAlertas
recordsYou can get GestaoAlertas
element from addresses
by ID
with either of these LINQ methods:
Pre-requisite:
Import System.Linq
namespace.
using System.Linq;
Solution 1: Enumerable.SingleOrDefault
Returns a single, specific element of a sequence, or a default value if that element is not found.
Note: It will throw InvalidOperationException
if input sequence contains more than one element. Good to be use for unique identifier such as ID.
GestaoAlertas _teste = addresses.SingleOrDefault(x => x.ID == ID);
Solution 2: Enumerable.Single
Returns a single, specific element of a sequence.
Note: It will throw ArgumentNullException
if it returns null
.
GestaoAlertas _teste = addresses.Single(x => x.ID == ID);
Solution 3: Enumerable.FirstOrDefault
Returns the first element of a sequence, or a default value if no element is found.
GestaoAlertas _teste = addresses.FirstOrDefault(x => x.ID == ID);
Solution 4: Enumerable.First
Returns the first element of a sequence.
Note: It will throw ArgumentNullException
if it returns null
.
GestaoAlertas _teste = addresses.First(x => x.ID == ID);