ICollection - Get single value

后端 未结 5 866
孤街浪徒
孤街浪徒 2021-02-03 17:45

What is the best way to get a value from a ICollection? We know the Collection is empty apart from that.

5条回答
  •  孤独总比滥情好
    2021-02-03 18:12

    The simplest way to do this is:

    foreach(object o in collection) {
      return o;
    }
    

    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:

    IEnumerator en = collection.GetEnumerator();
    en.MoveNext();
    return en.Current;
    

    If you know if may implement IList, you can do this:

    IList iList = collection as IList;
    if (iList != null) {
      // Implements IList, so can use indexer
      return iList[0];
    }
    // Use the slower way
    foreach (object o in collection) {
      return o;
    }
    

    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.

提交回复
热议问题