user441521
user441521

Reputation: 6998

Any() not giving what I would expect

delMo is a list of DateTime. I have it populated with 3/1/2014 and 4/1/2014. The results I get back is 2 records (what I expected) but the p.dt values for both records show 3/1/2014. I would expect 1 record to be 3/1/2014 and the other to be 4/1/2014.

My understanding of using Any() in this way is like using an in() statement in SQL. However, the results I get back don't seem to reflect this. Any ideas on what I did wrong here?

var result = (from p in db.Table1
             where (from dt in delMo
                    where p.dt == dt).Any()
                   &&
                   (from s in db.Stores
                    where p.storeID == s.ID).Any()
             select p).ToList();

[EDIT] I broke the problem down further and am getting very strange results. I hardcoded the store ID to 5 and it still gives me the problem. I even loop through delMo and pass in the 1 value to p.dt and on the first pass of 3/1/2014 I get the expected result. The second pass uses 4/1/2014 and it returns 3/1/2014!! If I only have 4/1/2014 in delMo then it works. It's like it's keeping the first 3/1/2014 record for some reason. It makes no sense.

Upvotes: 0

Views: 90

Answers (2)

Mat J
Mat J

Reputation: 5632

This should help. I wonder if P has a Stores collection, if it has, then it is more straightforward, but I'm not making assumptions.

(from p in db.Table1
  where delMo.Contains(p.dt)
        && db.Stores.Any(x=>x.ID==p.storeID)
  select p).ToList();

Note: Date should be exact match(including time) for this to work.

Upvotes: 0

Will Custode
Will Custode

Reputation: 4614

Any returns a bool indicating whether or not any elements in the collection satisfy a given condition. When used without a predicate, it indicates whether or not the collection contains elements. I'm not sure if that's what you meant by saying

in this way is like using in an in() statement

but that's what it does. See this link for more details.

As to your question in the comments, I believe something like this should do it. I'm not a huge fan of using linq over the IEnumerable extensions, so bear with me.

var result = db.Table1.Where( p =>
                delMo.Contains( p.dt ) &&
                db.Stores.Where( s=> s.ID == p.storeId ) );

This will return the values from db.Table1 where p.dt is in delMo and p.storeId is in db.Stores. Hope this helps!

Upvotes: 1

Related Questions