I cannot figure this out. The workflow of passing IEnumerable<T> (T is some my class, but it is not relevant here) basically looks like this:
var a = GetEntireCollection(); // so I get IEnumerable<T>
...
var b = a.Where(condition1);
...
var c = b.Where(condition2);
...
So I filter out more and more items from the collection, finally I call:
if (z.IsEmpty())
throw new Exception();
Foo(z);
and Foo is
public void Foo(IEnumerable<T> p)
{
pool = p.OrderByDescending(it => it.MyProperty).ToList();
if (pool.IsEmpty())
throw new Exception(pool.Count().ToString() + ", " + p.Count().ToString());
...
All I do, is order the collection.
Now, my program crashes with exception — it says that p has Count = 1, and pool has Count = 0. What’s more when I point out p and require the results (I run program using Visual Studio) it says, the collection yielded with no results (or somethig similar, not verbatim quote).
Questions:
- how can non-empty collection become empty just by reordering?
- how can collection Count can be > 0, when there are no items in it?
I am asking because I would like to know how to avoid this situation, but honestly, when I am looking at the code it seems 100% legit for me.
Technical background:
- it is pure C# code, no asm inlines, or anything like this
- no threads
- no external libraries, except for Where (which comes from Linq) this is all my code
Edits
Edit 1
public static bool IsEmpty<T>(this IEnumerable<T> coll)
{
var iter = coll.GetEnumerator();
return !iter.MoveNext();
}
Edit 2
Just before I call Foo(z) I check if the z is empty, so the code looks like this:
if (z.IsEmpty())
throw new Exception();
Foo(z);
SOLVED
As Jon suggested (C# sharpshooting I would say) one of the conditions was time dependent. So when the collection evaluation was forced the condition changed and I get in fact another collection.
One possibility is that evaluating the conditions twice is effectively changing the results.
Each time you iterate through
p, it will re-evaluate the data, including theWhereclauses. So you’re doing that once to populatepool, and then again to print outp.Count().Without any more information about what
GetEntireCollectiondoes or what theWhereconditions are, it’s hard to say what’s going on… but that’s one possible explanation. If you can post a short but complete program demonstrating the problem, that would help a lot.