Language Integrated Query (LINQ) is a cool feature of .NET languages like C# that allows you to perform SQL-like query right within the language against language’s data structures (lists, arrays etc.) But one drawback of LINQ – you have to know in advance, at compile time which fields to select, what filter conditions would be. Sometimes there’s a need to supply these at runtime – e.g. user selects which fields they want to see
Thankfully there exists Dynamic LINQ Library that allows you to supply LINQ parameters as a string akin Dynamic SQL. Here’s an example of such query from the library’s homepage:
var query = db.Customers .Where("City == @0 and Orders.Count >= @1", "London", 10) .OrderBy("CompanyName") .Select("new(CompanyName as Name, Phone)");
Now, one thing that LINQ can do is query XML. So in theory if we load, say, this XML:
<DATA_CENTER> <SERVER IP="1.2.3.4"> <OS>Windows</OS> </SERVER> <SERVER IP="5.6.7.8"> <OS>Linux</OS> </SERVER> </DATA_CENTER>
into an XElement and run something like this
var query0 = myXElement.Elements() .AsQueryable() .Select("new (Attribute(\"IP\").Value as IP, Element(\"OS\").Value as OS)")
it would produce list of IPs and OSes. Unfortunately this doesn’t work. Continue reading →