.NET Framework - constains or linq
Asked By raulav
28-Jul-08 02:11 PM
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
LINQ
(1)
ContainsKey
(1)
ToList
(1)
IEnumerable
(1)
Database
(1)
SecondaryIds
(1)
Andersson
(1)
MyClass
(1)
Nicholas Paldino [.NET/C# MVP] replied...
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]
- mvp@spam.guard.caspershouse.com
guff replied...
Neither.
Yes, of course. You are looping the collection, that doesn't scale well.
If you want to find the item quickly, you should use a Dictionary. The
ContainsKey method is close to O(1), meaning it's almost as fast
regardless of the number of items in the dictionary.
A Dictionary uses a hash code for the key, so you would need a key type
that contains the two fields that you check for, and a way to calculate
a hash code for that.
Incidentally, I wrote an article about using a Dictionary with a custom
key a while back:
http://www.codeproject.com/KB/cs/dictionary_customkey.aspx
--
Göran Andersson
_____
http://www.guffa.com
raulav replied...
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 [.NET/C# MVP] replied...

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]
- mvp@spam.guard.caspershouse.com
raulav replied...
greate! very good explanation...right on the nail Nicholas,thanks

source, and I have had very positive experiences of its Java cousin. As for Microsoft: LINQ to SQL will be released with .NET 3.5, but that only works with SQL will wait until ADO.NET 3 is released with SQL Server 2008, and with it LINQ to Entities. Whichever you choose, don't underestimate the importance of LINQ. Even if you don't plan to use C# 3 yet, you're likely to in the future, and LINQ is *lovely* where you can use it. (In some cases you may have a query which can't be expressed in LINQ, but that's okay.) As for backward compatibility: I wouldn't expect MS to release frameworks known to me. among many typical orm features, xpo is capable of creating the database structure on-the-fly (which means that you do not need any tables in your database and even then you still can persist objects). one of the most interesting features xpo the data using a simple webservice which is resposible for storing the data in the database. the client application thinks it stores the data in the database while in fact it
NET Framework Linq-to-Sql var null question or observation This is more an observation than a question MyMatchingTables = null, but rather I get zero hits (or .Count = 0). Must be built into Linq-to-Sql. I have been using it for years but this is the first time RL public List<MyTable> GetMyTablesByName(string aString) { List<MyTable> myMyTableList = new List<MyTable> (); try { DataContext database = new DataContext(MyConnectionString); var MyMatchingTables = from X in db.MyTables where X.AField.StartsWith(aString) select X; / / why is var MyMatchingTables never null? Must be built into Linq to Sql to never return null? myMyTableList = MyMatchingTables ToList(); } catch (Exception ex) { Debug.WriteLine(ex.Message); / / never triggered, even if no match } return myMyTableList That's what is coming out of the query even if you did not use ToList(), an empty List<T> being created. Now if you were using First() or FirstorDefault(), the the point So this could return a var MyMatchingTables = 3D null? But I thought in Linq-to-Sql that is not allowed? So it will throw an exception (in the try a row out of the table encapsulated as an object / entity, as that is what Linq does. What is Language Integrated Query? LINQ is a Microsoft .NET Framework component that adds
they're great - when used appropriately. They can greatly enhance the readability of code, and LINQ is a great example. Which do you think is clearer: 1) Without extension methods: IEnumerable<string> names = Enumerable.Select( (Enumerable.Where(people, person = > person.Age > 17), person = > person.Name); or IEnumerable<string> names = people.Where(person = > person.Age > 17) .Select(person = > person.Name); ? The latter gives abused. However, they allow a lot of really *nice* uses too - and enriching interfaces (as LINQ does) is probably the best use going. Of course, you can avoid using them yourself merely your opinion. Many people can and do disagree. One particular example: much of what LINQ provides would not work without extension methods. It relies on it heavily. But regardless, no of OO. Second, extension methods are the least kludgy way to work with objects in LINQ. Without extensions methods, LINQ would be both verbose and rather neutered. Used incorrectly, extension methods become a major cluster Methods? As far as I can see, a generic could have done the trick here: Linq<People> people; IEnumerable<string> names = 3D people.Where(person = 3D> person.Age > 17) .Select(person
NET Framework Is Linq to SQL any good? I am a big fan of linq but in my opinion linq to sql is a complete waste of time. Why on earth take something that is difficult to write by creating a translation layer. I see people here struggling to write linq to sql queries. It also creates the problem of being locked into a particular product with regards to the database which is exactly the problem I thought a translation layer would be designed to solve in newsgroups on those who disagree reply. :-) Thanks in advance, Michael If we ignore the LINQ to SQL vs LINQ to EF aspect. You should use LINQ to EF not LINQ to SQL. .NET wanted an ORM. Many people including me like