LINQ in Action

Fabrice Marguerie, Steve Eichert, Jim Wooley

Mentioned 12

Provides information on using LINQ to query XML, SQL databases, ADO.NET datasets, and other data sources and offers instructions on using LINQ to improve applications.

More on Amazon.com

Mentioned in questions and answers.

I have an asp.net application, and now I am using datasets for data manipulation. I recently started to convert this dataset to a List collection. But, in some places it doesn't work. One is that in my old version I am using datarow[] drow = dataset.datatable.select(searchcriteria). But in the List collection there is no method available for finding particular values. Is there any way for me to select some values according with my search criteria? I want to know if this is possible. Please help me.

Well, to start with List<T> does have the FindAll and ConvertAll methods - but the more idiomatic, modern approach is to use LINQ:

// Find all the people older than 30
var query1 = list.Where(person => person.Age > 30);

// Find each person's name
var query2 = list.Select(person => person.Name);

You'll need a using directive in your file to make this work:

using System.Linq;

Note that these don't use strings to express predicates and projects - they use delegates, usually created from lambda expressions as above.

If lambda expressions and LINQ are new to you, I would suggest you get a book covering LINQ first, such as LINQ in Action, Pro LINQ, C# 4 in a Nutshell or my own C# in Depth. You certainly can learn LINQ just from web tutorials, but I think it's such an important technology, it's worth taking the time to learn it thoroughly.

Basically what the title says. (Forgive me because I am a .NET newb)

In my department, we have a server running .net 3.5 and ever since I got into this section I have been using LINQ. However, I am starting a personal project on a different server (obviously), so 2 questions:

What do I need to get up and running with LINQ?

What does the server need to run LINQ?

Will .net 2.0 work on the server?

The code behind would be C# if that matters.

Edit: Would I have to compile it in 3.5 or would 2.0 work?

To get up and running, I would definitely recommend checking out LINQ in Action.

alt text

Your compiler needs to be .NET 3.5 framework. If you are copying over only compiled code, then you will not need 3.5 on your server, you only need it on your development machine. This can help if your server admin is unwilling to install the 3.5 framework on your server. However, if you are publishing source code, say to a development server to compile, then yes that server will need 3.5.

Once you have the 3.5 framework installed, you can run web apps either as 2.0 or 3.5. All you have to do is specify it in your Web.Config file.

If you are interested in working with LINQ to SQL and managing dbml files, you will need Visual Studio 2008. However, Visual Studio 2005 will still compile dbml files properly, given that you have the 3.5 framework installed.

Ok here is my situation. I've studied Java in my college for 2 semesters. But you know they teach you jack in there, just the basics. We skipped half of our textbook and even then our professors don't teach from section to section of each chapter. I don't blame them. It's hard as it is for new students to understand even the basic concepts of programming. Now this is a community college we are talking about and not Stanford, MIT or Berkeley.

So like I said I've done 2 semester of Java. I really like our textbook because it has some challenging projects to do at the end of each chapter. This textbook is pretty clear and i have no problem understanding it (although 2-D and 3-D Arrays have given me some trouble). I have tried reading a few C# books such as Pro C# 2008 and .NET 3.5 and C# 4.0 in a Nutshell. I found these books to be dry and overloaded with information that put me to sleep (No offense to the authors of those 2 wonderful, according to amazon ratings, books).

Would you suggest I finish my Java textbook, brush up my knowledge of Arrays, Polymorphism, and etc that are universal to most programming languages. And then switch to C#, plus the syntax is very similar so it should be easy to switch. Or should I just start learning C# right now from the very beginning? If it's the latter then could you recommend some free online resources that will keep me engaged and at the same time teach me everything I need to know about C#.

Someone has recommended me to learn .NET first, but I found it to be not the brightest idea. .NET is just a big monster full of libraries. How am I going to apply it if I don't even know the C# or VB!? Anyway back to my question: Master Java and switch to C# or just go with C#?

DISCLAIMER: I don't want to start .NET vs J2EE or C# vs Java flame war. I am going with C#. I've decided that I want to work in a Microsoft shop in the future. .NET is what I want to learn.

Thanks! Will be waiting for the answers.

I think I found the answer to your question...in your question.

For now, go ahead and finish your Java book as a way of continuing to learn the fundamentals of OOP.

Next (or while finishing the Java book), shift your focus to C# and the .NET framework (in most business situations, you'll be hard-pressed to find one without the other).

If you want to focus more on language elements of C# rather than a specific framework (such as ASP.NET, Silverlight, Windows Forms, or WPF, to name a few things), you might consider a book on LINQ, such as LINQ in Action from Manning Press. Combine your knowledge of LINQ with trying to solve some problems at http://projecteuler.net and you should start picking up the language pretty quickly.

Personally, I read Illustrated C# 2008 by Daniel Solis. Granted, it's not a textbook filled with lots of fun and challenging examples, but it is a good exposition of the language.

I have a couple of LINQ to SQL queries that I feel take a lot of time. What tool and techniques can I use to first find out:

  1. How long they take and if there is room for improvement?
  2. Find out what I can change and easily test if those changes are effective?

Both tools, techniques and reading resources would be appreciated (ergo up-voted ;))

I just attended a LINQ Tools presentation at a recent codecamp event given by Jim Wooley, one of the authors of LINQ In Action. He blogged about all the tools. Here are the ones that relate to your question, but his post lists other goodies to look into.

  • SQL Server Profiler ($$$) - part of the SQL Management Studio.

  • Huagati LINQ to SQL Profiler ($$$, 45-day trial) - Profiler which extends the Context.Log functionality. Includes performance and call stacks for the queries beyond what you get with SQL Server Profiler.

  • LINQ to SQL Visualizer (free) - part of the C# Samples for VS2008. Download, compile, enjoy!

  • LINQPad (free, pay for C# Intellisense) - light-weight tool to run C#/VB.NET code, connect to DBs, test Linq to SQL, view the generated SQL etc.

I was just looking through this stack overflow question: What's the hardest or most misunderstood aspect of LINQ? and I couldnt believe I was using so many of these concepts sometimes correctly and sometimes incorrectly.

Can you guys please direct me to a book/blog that explains all these concepts. It would be really cool to understand all the details

Thanks in advance

Double thumbs up for Jon Skeet's Edulinq series :) Read this article LINQ Secrets Revealed: Chaining and Debugging. Also check LINQ in Action and LINQ Pocket Reference books. Cheers!

Good day!

I'm currently building a small website where I write down problems that arise and answers to them for others to see. Currently I'm using a DAL much like the one described here. Now I have been looking at other models, and in particular linq based models using Linq2SQL and the ADO.net Entries framework. I realize I'm moving the data access to the code layer in a way since I'm then filtering out for example a toplist with linq queries. The reason I started doing this was because the DAL was not really syncing up with the DB at all times and nullable types became not nullable when I changed something in the DB. Then if I would reimport the tables into the data table my queries would be lost.

My simple question is really, if you want a good DAL for ASP.net today, what would that be? Suggestions, experiences are more than welcome.

I personally preffer LINQ to SQL and ADO.NET Entity Framework. Microsoft guys also use those technologies in their latest projects (take a look at KOBE project for example). Thus, Microsoft recommends those two as well.

Though.. sometimes I use Data Access Application block from Enterprise Library and manual DAL coding when I need maximum control over it's functionality and implementation.

Other alternatives are: NHibernate, SubSonic, different ORM solutions like LLBLGen Pro.


Great books on this subject:


Related tools:

  • LINQPad is also a great way to learn LINQ: it comes preloaded with 200 examples from the book, C# 3.0 in a Nutshell. There's no better way to experience the coolness of LINQ and functional programming.

I am learning Windows Forms in C#.NET 2008 and i want to build a class to work with SIMPLE xml files (config file like INI files), but i just need a simple class (open, getvalue, setvalue, creategroup, save and close functions), to substitute of ini files.

I already did something and it is working but I am having trouble when I need to create different groups, something like this:

<?xml version="1.0" encoding="utf-8"?>
<CONFIG>
  <General>
    <Field1>192.168.0.2</Field1>
  </General>
  <Data>
    <Field1>Joseph</Field1>
    <Field2>Locked</Field2>
  </Data>
</CONFIG>

how can i specify that i want to read the field1 of [data] group? note that i have same field name in both groups (Field1)!

I am using System.Linq, something like this:

To open document:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath);

To save document:

xmlDoc.Save(FilePath);

To get value:

public string getValue(string Field)
{
    string result = "";
    try
    {
        XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field);
        if (xmlComum.Item(0) == null)
            result = "";
        else
            result = xmlComum.Item(0).InnerText;
    }
    catch (Exception ex)
    {
        return "";
    }
    return result;
}

To set value:

public void setValue(string Group, string Field, string FieldValue)
{
    try
    {
        XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field);
        if (xmlComum.Item(0) == null)
        {
            xmlComum = xmlDoc.GetElementsByTagName(Group);
            if (xmlComum.Item(0) == null)
            {
                // create group
                createGroup(Group);
                xmlComum = xmlDoc.GetElementsByTagName(Group);
            }
            XmlElement xmlE = xmlDoc.CreateElement(Field);
            XmlText xmlT = xmlDoc.CreateTextNode(FieldValue);
            xmlE.AppendChild(xmlT);
            xmlComum.Item(0).AppendChild(xmlE);
        }
        else
        {
            // item already exists, just change its value
            xmlComum.Item(0).InnerText = Value;
        }
        xmlDoc.Save(FilePath);
    }
    catch (Exception ex)
    {
    }
}

The CreateGroup code:

public void createGroup(string Group)
{
    try
    {
        XmlElement xmlComum = xmlDoc.CreateElement(Group);
        xmlDoc.DocumentElement.AppendChild(xmlComum);
        xmlDoc.Save(FilePath);
    }
    catch (Exception ex)
    {
    }
}

Though you may be "using" System.Linq in your project, you are not using the so-called "Linq-to-XML" classes. Which make things about 5 times easier, even you're not using LINQ on them! Use the System.Linq.XML namesspace, to have access to these new xml classes (XDocument, XElement, etc.)

    XDocument XDoc = XDocument.Load("ThePath") 
    String Field1 = (String)XDoc.Root.Element("Data").Element("Field1")

i am searching a good book to learn ADO.NET 4.0, book should be excellent technical overview with practical examples, I want to learn ADO.NET Where should I start?

ADO.Net may be a pretty broad topic. Here are some books that I've had success with:

This is my first question and first day in Linq so bit difficult day for me to understand. I want to fetch some records from database

i.e.

select * from tblDepartment 
where department_id in 
(
   select department_id from tblMap 
   where Guest_Id = @GuestId
)

I have taken two DataTable. i.e. tblDepartment, tblMap

Now I want to fetch this result and want to store it in third DataTable.

How can I do this.

I have been able to construct this query up till now after googling.

var query = from myrow in _dtDepartment.AsEnumerable()
            where myrow.Field<int>("Department_Id") == _departmentId
            select myrow;

Please provide me some link for learning Linq mainly for DataTables and DataSets.

EDIT:

I have got a very similar example here but i m still not able to understand how it is working. Please put some torch on it.

I want to do this because I am already fetching data from database and dont want to send request again when I already have data. But I want to filter that data based on conditions.

What you are attempting is not actual LINQ-To-SQL. It is a common misunderstanding. In LINQ-To-SQL you map some tables to entities in a simple way, then at run-time your LINQ query is translated by SQL by the framework and returned as your pre-defined strongly typed entity objects. (I use "entity" as a descriptive term; nothing to do with Entity Framework.) LINQ-To-SQL is something you do instead of ADO.NET.

What you are doing is a flavor of LINQ-to-object often called "LINQ-To-Dataset", which I use often. The extension method .AsEnumerable() returns a DataTable's DataRows in an IEnumerable<DataRow> object, which is very handy. However, with LINQ-To-DataTable, you either (A) won't have strongly typed objects, or (B) you are taking responsibility for putting your data into strongly typed objects yourself. After you've used ADO.NET like you always have, LINQ-to-DataTable is a great way to get your data out of ADO.NET DataTables and into something else, whatever is consuming the data.

You LINQ query above will take your DataTable, which has already run against the DB, and return an IEnumerable<DataRow>, which is great. Do:

After your LINQ statement, do:

For Each DataRow in query
    //Do your stuff
Next

If you really need a DataTable object in particular at this point, then check this out. But do you really need a DataTable?

And I have to suggest a really great book about LINQ. LINQ rocks. In a .NET world that seems to have too much that we need to learn, LINQ is worth taking the time to really understand. Get: LINQ In Action.

I have a web application. It does a TON of data reads on small tables and a few writes. I want to pull entire tables of data into cache, and query the cached data. I override the context's Table<T>() method so we can serve cache instead of live data. Works great for inserts and supports unit testing data access as well. Awesome.

So we started using cache data and discovered that updates and deletes don't work.

We pull an object from db, throw it into a List<T>, put that list in the httpCache, then drop the data context.

Two requests later, we call the overridden Table<T>, it gets the list, and pulls the object out. We change it and then need to attached the cached, then changed object to the db context. So we call myContext.Attach(myobject) and.....BOOM

An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.

Is there a way around this limitation?

It sounds like your cached entities are still attached to the original DataContext that they were queried with. One way around this (that breaks the best-practice rule of keeping the DataContext life-cycle short) is to cache the DataContext along with your entities, and then use that cached context when you want to delete or update the cached entities.

You mention that the cached entities are used "two requests later" - if those requests all occur within a short timespan, then breaking short-life-cycle rule might not be an issue.

Another option is to cache objects that are based on entities but that are not entities, and when it's time to update entities with values stored in the cached non-entity objects, query clean entities on a new DataContext, update those entities and save then on the newly-created DataContext.

There are yet other ways to do it - I've found the book LINQ in Action to be very helpful in dealing with cases like these.

I've just started working with LINQ (mainly in context of the ADO.NET Entity Framework) and currently learning the basics from The ADO.NET Entity Framework Overview @ MSDN and this LINQ tutorial.

Any other online primers recommended for beginners to learn LINQ fundamentals? I generally do know the syntax and how to get the objects I need but learning more should help me to write more efficient code.

Thanks!

Im a book guy and I can recommend you two books:

Linq In action
Beginning ASP.NET 4

That are two books I have read. The second one use Linq to ADO.NET EF (A very good introduction).

At least you should consider the first book as a very good intro to LINQ. (You read the parts you want obviously :))

How to get started learning LINQ in C#.net.

LINQ is a pretty big subject.

I would start with Hooked On LINQ

The way I learned Linq was from the book Linq in Action