Suppose I have a class AddressType defined as is:
public class AddressType {
public int AddressTypeId { get; set; }
public string Description { get; set; }
}
Having a List object in code, how do I select an AddressType object with a known AddressTypeId property?
I have never used the List.Where extension function….
Thanks!
You can get all
AddressTypeobjects in the list having a specific ID by usingWhere:But if you only want the one and only
AddressTypehaving a specific ID you can useFirst:This will find the first
AddressTypein the list having ID 123 and will throw an exception if none is found.Another variation is to use
FirstOrDefault:It will return
nullif noAddressTypehaving the requested ID exists.If you want to make sure that exactly one
AddressTypeexists in the list having the desired ID you can useSingle:This will throw an exception unless there is exactly one
AddressTypein the list having ID 123.Singlehas to enumerate the entire list making it a slower thanFirst.