What is the best way to get a value from a ICollection? We know the Collection is empty apart from that.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
If you know your collection has only one item, should only ever have one item, you can use the Linq extension method
Single()
.This converts a
ICollection<T>
into aT
object containing the single item of that collection. If the length of the collection is 0, or more than one, this will throw anInvalidOperationException
.Without generics and because
ICollection
implementsIEnumerable
you can do like in example 1. With generics you simple need to do like example 2:The simplest way to do this is:
But this isn't particularly efficient if it's actually a generic collection because IEnumerator implements IDisposable, so the compiler has to put in a try/finally, with a Dispose() call in the finally block.
If it's a non-generic collection, or you know the generic collection implements nothing in its Dispose() method, then the following can be used:
If you know if may implement IList, you can do this:
Likewise, if it's likely it'll be of a certain type of your own definition that has some kind of indexed access, you can use the same technique.
Linq, baby, yeah...
I personally prefer this method to go from a singleton of type
ICollection<T>
toT
. It is just as simple asFirstOrDefault()
butSingle()
throws if the collection does not have a single element. So it gives a better guarantee of correctness than usingFirstOrDefault()
..
This way is slow, but very simple to use