ICollection - Get single value

2019-03-11 14:29发布

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

6条回答
爷的心禁止访问
2楼-- · 2019-03-11 14:38

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 a T object containing the single item of that collection. If the length of the collection is 0, or more than one, this will throw an InvalidOperationException.

查看更多
Ridiculous、
3楼-- · 2019-03-11 14:40

Without generics and because ICollection implements IEnumerable you can do like in example 1. With generics you simple need to do like example 2:

List<string> l = new List<string>();
l.Add("astring");

ICollection col1 = (ICollection)l;
ICollection<string> col2 = (ICollection<string>)l;

//example 1
IEnumerator e1 = col1.GetEnumerator();
if (e1.MoveNext())
    Console.WriteLine(e1.Current);

//example 2
if (col2.Count != 0)
    Console.WriteLine(col2.Single());
查看更多
Viruses.
4楼-- · 2019-03-11 14:48

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.

查看更多
别忘想泡老子
5楼-- · 2019-03-11 14:55

Linq, baby, yeah...

   var foo = myICollection.OfType<YourType>().FirstOrDefault();
    // or use a query
    var bar = (from x in myICollection.OfType<YourType>() where x.SomeProperty == someValue select x)
       .FirstOrDefault();
查看更多
Summer. ? 凉城
6楼-- · 2019-03-11 14:55
using System.Linq;


collection.Single();

I personally prefer this method to go from a singleton of type ICollection<T> to T. It is just as simple as FirstOrDefault() but Single() throws if the collection does not have a single element. So it gives a better guarantee of correctness than using FirstOrDefault().

查看更多
Viruses.
7楼-- · 2019-03-11 15:00

.

collection.ToArray()[i]

This way is slow, but very simple to use

查看更多
登录 后发表回答