小智 75
林奇,宝贝,是啊......
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();
Run Code Online (Sandbox Code Playgroud)
Chr*_*ris 21
最简单的方法是:
foreach(object o in collection) {
return o;
}
Run Code Online (Sandbox Code Playgroud)
但是如果它实际上是一个通用集合,这并不是特别有效,因为IEnumerator实现了IDisposable,所以编译器必须放入try/finally,在finally块中调用Dispose().
如果它是非泛型集合,或者您知道泛型集合在其Dispose()方法中没有实现任何内容,则可以使用以下内容:
IEnumerator en = collection.GetEnumerator();
en.MoveNext();
return en.Current;
Run Code Online (Sandbox Code Playgroud)
如果您知道是否可以实现IList,则可以执行以下操作:
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;
}
Run Code Online (Sandbox Code Playgroud)
同样,如果它可能是某种类型的您自己的定义具有某种索引访问权限,则可以使用相同的技术.
.
collection.ToArray()[i]
Run Code Online (Sandbox Code Playgroud)
这种方式速度慢,但使用起来非常简单
没有泛型,因为ICollection实现,IEnumerable你可以像示例 1 那样做。 使用泛型,你只需像示例 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());
Run Code Online (Sandbox Code Playgroud)