-1

I have a c# code as below, Its showing error at IEnumerable<\u003C\u003Ef__AnonymousType0 Can someone tell me how to solve it.

dataSet = this.GetData.getInfo("SELECT b.nBatchID, td.F_Name &' '& td.M_Name &' '& td.L_Name AS StaffName, b.BatchName FROM (Batch AS b LEFT JOIN BatchTrainer AS bt ON b.nBatchID = bt.nBatchId) LEFT JOIN TrainerDetails AS td ON bt.TrainerId = td.TrainerID", "Batch");
            IEnumerable<\u003C\u003Ef__AnonymousType0<object, string, string>> datas = dataSet.Tables[0].Copy().AsEnumerable().GroupBy<DataRow, object>((Func<DataRow, object>) (row => row["nBatchId"])).Select(g =>
            {
              var data = new{ id = g.Key, text = string.Join(",", g.Select<DataRow, string>((Func<DataRow, string>) (r => r["StaffName"].ToString())).ToArray<string>()), Batch = g.Select<DataRow, string>((Func<DataRow, string>) (r => r["BatchName"].ToString())).FirstOrDefault<string>() };
              return data;
            });
            table.Columns.Add("nBatchId", typeof (int));
            table.Columns.Add("StaffName", typeof (string));
            table.Columns.Add("BatchName", typeof (string));
            foreach (var data in datas)
              table.Rows.Add(data.id, (object) data.text, (object) data.Batch);
            dataSet.Tables.Clear();
            dataSet.Tables.Add(table);
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Amaan Khan
  • 181
  • 2
  • 3
  • 15

1 Answers1

6

Don't specify type name when you deal with anonymous types. Use var instead to make compiler infer type for you:

var datas = dataSet.Tables[0].Copy().AsEnumerable()
             .GroupBy(row => row.Field<int>("nBatchId"))
             .Select(g => new { 
                 id = g.Key, 
                 text = string.Join(",", g.Select(r => r.Field<string>("StaffName")),
                 Batch = g.Select(r => r.Field<string>("BatchName")).FirstOrDefault()
             });

Other considerations:

  • Don't specify generic parameters for LINQ extension methods. Compiler will infer generic parameters from type of source sequence
  • Don't specify type of predicate for LINQ extension methods. Same as above, compiler will infer type from source sequence
  • Use Field<T>("columnName") extension for DataRow to get nicely typed cell values
  • Don't create copy of DataTable just for querying it. LINQ will not modify original DataTable
  • Don't put values which you are passing to String.Join method into array. There is method overload which accepts IEnumerable<T>
Bakudan
  • 19,134
  • 9
  • 53
  • 73
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459