raulavi,
Well, it depends. If this is a LINQ to SQL query, then the query is
composed and sent to the server, and you don't have to worry about out of
memory exceptions (generally speaking).
With this particular query, you don't have deferred execution (the Any
method returns a boolean, not an IEnumerable<T> which can be deferred) so it
will be executed on that line of code. If you are going to wrap anything in
a try/catch block, it's that line.
If this is all in memory, then you shouldn't run across exceptions due
to lack of memory, because it is assumed that the collection is already in
memory (unless you are streaming it through an IEnumerable<T> implementation
and the results are being created on the fly, which I don't think is the
case).
As far as performance, the Any method is going to finish terminating the
moment it runs across a condition that is true, just like your loop, so I
expect the performance characteristics to be the same.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
raulavi said:
thanks, they are and you are right....
Your sample is much better and that's exactly what I want.
I also wanted to know performance wise.
the only problem I may expect is if my sample of linq is ran on a very
large
database, it might ran out of memeory, correct? then , if so, how do you
trap
the error, try/catch and where can i read about what exceptions might
throw?
Nicholas Paldino said:
raulavi,
I would think so. In the first, you are just checking for the
existence
of one object that satisfies the condition. In the second, you are
getting
all of the objects that satisfy the condition. What you really want to
do
is the following:
bool matches = SecondaryIds.Any(r => r.field01 = type && r.field02 ==
id);
That will give you the same result as the first (assuming the
collections are the same, as the code you use doesn't indicate that they
are).
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
linq on objects...
want to find if the object exist in its collection
if I have a loop searching in the collection
foreach (myClass r in collections)
{
if (r.field01 == type && r.field02 == id)
return true;
}
return false;
versus
Linq
List <myClass> qq =
(from r in SecondaryIds
where r.field01 == type && t.field02 == id
select t).ToList();
1. any performance issues. (lets say there are many obj in collection)
2. how do get collection count from linq or can I set a true variable
if
found?
thanks