tags:

views:

271

answers:

2
+2  Q: 

Dynamic LINQ

I have an XML document defined like so

XML File

<TABLE>
    <RECORD>
     <PAGENUMBER> 1 Of 1</PAGENUMBER>
     <OtherFields1>..</OtherFields1>
     <OtherFields2>..</OtherFields2>
    </RECORD>
    <RECORD>
     <PAGENUMBER> 1 Of 2</PAGENUMBER>
     <OtherFields1>..</OtherFields1>
     <OtherFields2>..</OtherFields2>
    </RECORD>
    <RECORD>
     <PAGENUMBER> 2 Of 2</PAGENUMBER>
     <OtherFields1>..</OtherFields1>
     <OtherFields2>..</OtherFields2>
    </RECORD>
    <RECORD>
     <PAGENUMBER> 1 Of 1</PAGENUMBER>
     <OtherFields1>..</OtherFields1>
     <OtherFields2>..</OtherFields2>
    </RECORD>
</TABLE>

I'm trying to create a dynamic query where i can put a "Fieldname", "Operand", "Value" in a config and LINQ can build a predicate based on it.

Config File

<CLAUSES>
    <CLAUSE name="PAGENUMBER" operand="!=">Page 1 Of 1</CLAUSE>
    <CLAUSE name="OtherFields1" operand="!=">String.Empty</CLAUSE>
</CLAUSES>

Here is the LINQ i'm using now

LINQ Query

        XDocument jobXML = XDocument.Load(JobFile);

        List<ClauseObj> clauses = new List<ClauseObj>();
        clauses.Add(new ClauseObj { Field = "PAGENUMBER", Operand = "!=", Value = " Page 1 Of 1" });

        var q = jobXML.Descendants("RECORD").AsEnumerable();

        foreach (var c in clauses)
        {
            switch (c.Operand)
            {
                case "!=":
                    q = q.Where(r => r.Element(c.Field).Value != c.Value);
                    break;
            }
        }

how can i make it read the where clauses "dynamically" and also specify which field names to return?

+1  A: 

Have a look at the Dynamic Linq Queries Sample. They have a class in there that adds various extensions methods for Where and Order By

JoshBerke
I've already looked at it it, and I've attempted to use it to avail.Maybe an example in my use case would be more helpful ?
Michael G
Ohn you need the select dynamic as well hmm...no idea...but you should be able to use it to get rid of your switch.
JoshBerke
+1  A: 
string clause = "PAGENUMBER";
string operand = "!=";
string value= " Page 1 Of 1";

  var q = from r in jobXML.Descendants("RECORD")
                 select new
                 {
                     PAGENUMBER = (string)r.Element("PAGENUMBER"),
                     OtherFields1 = (string)r.Element("OtherFields1")
                 }

   switch(operand)
   {
       case "!=":
          q = q.Where(r=> r.Element(clause).Value != value);
          break;
       case "etc":
   }

   var list = q.ToList();
James Curran
that's close; but what about the select area being dynamic ?
Michael G
close enough; i'll figure the rest out! thanks
Michael G