How to create a dynamic LINQ join extension method

前端 未结 3 1500
难免孤独
难免孤独 2020-11-27 13:55

There was a library of dynamic LINQ extensions methods released as a sample with Visual Studio 2008. I\'d like to extend it with a join method. The code below fail

3条回答
  •  时光说笑
    2020-11-27 14:12

    Here is some sample code showing a join on multiple columns. Using a datatable and datarows you need to always access fields via the indexer.

      DataTable t1 = new DataTable();
      t1.Columns.Add("FundId", typeof(int));
      t1.Columns.Add("Date", typeof(DateTime));
      t1.Columns.Add("CodeA", typeof(string));
      t1.Rows.Add(1, new DateTime(2010, 01, 01), "A1");
      t1.Rows.Add(2, new DateTime(2010, 01, 01), "A2");
      t1.Rows.Add(3, new DateTime(2010, 01, 01), "A3");
    
      DataTable t2 = new DataTable();
      t2.Columns.Add("FundId", typeof(int));
      t2.Columns.Add("Date", typeof(DateTime));
      t2.Columns.Add("CodeB", typeof(string));
      t2.Rows.Add(1, new DateTime(2010, 01, 01), "B1");
      t2.Rows.Add(2, new DateTime(2010, 01, 01), "B2");
      t2.Rows.Add(3, new DateTime(2010, 01, 01), "B3");
    
      IQueryable outerTable = t1.AsEnumerable().AsQueryable();
      IEnumerable innerTable = t2.AsEnumerable();
    
      var query = outerTable.Join
        (
          innerTable, 
          "new(get_Item(0) as FundId, get_Item(1) as Date)",
          "new(get_Item(0) as FundId, get_Item(1) as Date)",
          "new(outer.get_Item(0) as FundId, outer.get_Item(2) as CodeA, inner.get_Item(2) as CodeB)"
        );
    

提交回复
热议问题