5

Assume I have a DataTable with three columns C1, C2, C3:

var dt = new DataTable();
dt.Columns.Add("C1", typeof (int));
dt.Columns.Add("C2", typeof (string));
dt.Columns.Add("C3", typeof(string));

dt.Rows.Add(1, "1", "1");
dt.Rows.Add(1, "1", "2");
dt.Rows.Add(1, "2", "2");

I use Dynamic Linq on nuget to GroupBy columns C1 and C2 like the code below and it works perfectly:

 var output = dt.AsEnumerable()
            .AsQueryable()
            .GroupBy("new(it[\"C1\"] as C1, it[\"C2\"] as C2)", "it");

If you notice, there is a hardcode string it to present as DataRow, I get this idea from:

Dynamic Linq GroupBy

. If I try changing it to string row for example:

GroupBy("new(row[\"C1\"] as C1, row[\"C2\"] as C2)", "row");

I will get runtime error:

No property or field 'row' exists in type 'DataRow'

So, I don't clear up my mind much why having to hardcode it as DataRow? Is there any reason for this.

Community
  • 1
  • 1
cuongle
  • 74,024
  • 28
  • 151
  • 206

2 Answers2

1

That's just how the Dynamic LINQ provider is written. It has three hard-coded keywords that it recognizes when it tries to parse the LINQ expressions: it, iff, and new:

static readonly string keywordIt = "it";
static readonly string keywordIif = "iif";
static readonly string keywordNew = "new";

You can check the source to the LINQ assembly yourself if you want to see more details.

(BTW: "it" here appears to be short for "identifier token", if I had to guess.)

Michael Edenfield
  • 28,070
  • 4
  • 86
  • 117
  • 1
    Yes, because your Dynamic LINQ strings are compiled into a Lambda expression, and requires an input parameter. Since there is no way for you to specify what that input parameter is called, they just use the keyword "it" to reference the element of the enumerable. In other words, the `Select("...")` call gets compiled into `Select(it => ...)` – SPFiredrake Mar 01 '13 at 18:44
0

Well I suppose they had to call the current object in the enumeration 'something', so 'it' seems like a reasonable choice.

Mau
  • 14,234
  • 2
  • 31
  • 52