我有以下在 .NET Framework 版本 4.0 及更高版本中编译的代码:
public abstract class MyBase { }
public class MyDerived : MyBase { }
public abstract class MyBaseCollection<T> : IList<T> where T : MyBase
{
protected readonly IList<T> deriveds = new List<T>();
public void Test()
{
// This line works in .NET versions 4.0 and above, but not in versions below.
IEnumerable<MyBase> bases = deriveds;
}
#region IList members with NotImplementedException
// ...
#endregion
}
public class MyDerivedCollection : MyBaseCollection<MyDerived> { }
Run Code Online (Sandbox Code Playgroud)
但在 4.0 以下的 …
我想以这样的方式迭代一些列表项,即从特定位置开始,然后从它向左走,然后从它向右走。
换句话说,是这样的:
var items = new List<string>() { "Item1", "Item2", "Item3", "Item4", "Item5" };
string item = "Item3";
int index = items.IndexOf(item);
for (int i = index; i >= 0; i--)
yield return items[i];
for (int i = index + 1; i < items.Count; i++)
yield return items[i];
Run Code Online (Sandbox Code Playgroud)
结果是:Item3
, Item2
, Item1
, Item4
,Item5
有没有一种方法可以实现这一目标,但只使用一个 for 循环?
或者 LINQ 中有某种条件方向吗?