Why does IEnumerable inherit from IEnumerable?

Straight from the horse’s mouth (Hejlsberg): Ideally all of the generic collection interfaces (e.g. ICollection<T>, IList<T>) would inherit from their non-generic counterparts such that generic interface instances could be used both with generic and non-generic code. For example, it would be convenient if an IList<T> could be passed to code that expects an IList. As … Read more

Using IEnumerable without foreach loop

You can get a reference to the Enumerator, using the GetEnumerator method, then you can use the MoveNext() method to move on, and use the Current property to access your elements: var enumerator = getInt().GetEnumerator(); while(enumerator.MoveNext()) { int n = enumerator.Current; Console.WriteLine(n); }

Why Enumerable.Cast raises an InvalidCastException?

Well, you have incorrect expectations of Cast, that’s all – it’s meant to deal with boxing/unboxing, reference and identity conversions, and that’s all. It’s unfortunate that the documentation isn’t as clear as it might be 🙁 The solution is to use Select: doubleNumbers2 = intNumbers.Select(x => (double) x).ToArray();

Remove items from IEnumerable

I don’t see how the first version would compile, and the second version won’t do anything unless you use the result. It doesn’t remove anything from the existing collection – indeed, there may not even be an in-memory collection backing it. It just returns a sequence which, when iterated over, will return the appropriate values. … Read more