Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Thursday, 6 August 2009

Using Linq lambda expressions to retrieve XML elements based on the value of an attribute

The following example program loads an XML file, then selects all the elements named "field" within it. It then uses a lambda expression to get the inner text of the "alternativeTitle" element.

class Program
{
static void Main( string[] args )
{
XDocument xd = XDocument.Load( "..\\..\\file.xml" );

var fields = from el in xd.Descendants()
where el.Name.ToString().StartsWith( "field" )
select el;

Console.WriteLine( GetElementValue(fields, "alternativeTitle") );
Console.ReadLine();
}

static string GetElementValue( IEnumerable<XElement> elements, string attributeName )
{
return elements.Single( p => p.Attributes().Single( q => q.Name == "name" ).Value == attributeName ).Value;
}
}

The XML file used in the example is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<add>
<doc>
<field name="id">some_id</field>
<field name="readableid">interesting_publications</field>
<field name="name">Interesting Publications</field>
<field name="alternativeTitle">Online publications</field>
</doc>
</add>

The program outputs the text:

Online publications

Tuesday, 14 October 2008

Always set AutoPage to true in LinqDataSource

If you are binding a control to a LinqDataSource, always set the AutoPage property on the LinqDataSource to true (AutoPage=“true”) if you have enabled paging on the data-bound control. Without the AutoPage option set, the LinqDataSource will pull back all records in the data source every time a page is browsed. Not only is this inefficient and not scalable, but it allows the client to determine the level of resources required, which is not good practice.

<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="MyDataContext" TableName="MyTable" AutoPage="true"></asp:LinqDataSource>

Sadly, the AutoPage option doesn’t seem to be available in other DataSource objects, so a manual implementation is necessary for these.

Friday, 7 December 2007

LINQ to Everything

Last month, as I was leaving the excellent .NET Developer Network in Bristol, I was considering the various data sources that can be queried using LINQ. There's LINQ to XML, LINQ to objects, LINQ to SQL and so on. As I was just about to leave building, I walked past a sign showing the words "Link to P Block". And suddenly, everything seemed all right with the world.

Technorati Tags: LINQ