Is there a quick way to Find an object in a List<T> without looping through the List or using Linq? Yes; use the Find Method of the object.
If you are new to .NET, or even if you have been using it for years, but you still have outdated ways of doing things, you might be waisting developement time, resources, and performance if you do not keep up to date on new features that the .NET framework brings to the table for algorithms that you use all the time.
For example, if you need to find an object in a generic List<T>, you might still be using code like the code shown below. Suppose that you have a List<Address> and the Address object has an IsPrimary field (bool). One and only one of the objects can be primary and you need to retrieve the primary address object from the List. The "user" object has an Addressess property which is a List<Address>. The tried and proven (over and over) method for doing this would be:
| Address primaryAddress; foreach (Address addr in user.Addresses) { if (addr.IsPrimary) { primaryAddress = addr; break; } // if } // foreach |
| Address primaryAddr = user.Addresses.Find(delegate(Address obj) { return obj.IsPrimary; }); |
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |