views:

38

answers:

2

Hello,

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!

A: 
IEnumerable<AddressType> addressList = ...
IEnumerable<AddressType> addresses = addressList.Where(a => a.AddressTypeId == 5);

or:

IEnumerable<AddressType> addresses = 
    from address in addressList
    where address.AddressTypeId == 5
    select address;
Darin Dimitrov
+2  A: 

You can get all AddressType objects in the list having a specific ID by using Where:

IEnumerable<AddressType> addressTypes = list.Where(a => a.AddressTypeId == 123);

But if you only want the one and only AddressType having a specific ID you can use First:

AddressType addressType = list.First(a => a.AddressTypeId == 123);

This will find the first AddressType in the list having ID 123 and will throw an exception if none is found.

Another variation is to use FirstOrDefault:

AddressType addressType = list.FirstOrDefault(a => a.AddressTypeId == 123);

It will return null if no AddressType having the requested ID exists.

If you want to make sure that exactly one AddressType exists in the list having the desired ID you can use Single:

AddressType addressType = list.Single(a => a.AddressTypeId == 123);

This will throw an exception unless there is exactly one AddressType in the list having ID 123. Single has to enumerate the entire list making it a slower than First.

Martin Liversage
@Martin: thanks a lot!
Lorenzo