0

I have a linq query in which I need to be able to select an variable number of fields from a datatable. I do know all of the fields that could be included, but only two will for sure be in the datatable. I also will know which fields are included in the datatable (it will just be different depending on the user's selections). Right now I set up something like this:

var query = from item in dt.AsEnumerable()
            group item by item.Field<string>("ID") into g
            select new
            {
                ID = g.Key, //required
                Status = g.Min(i => dostuff(i,"Status")), //not required
                Disc = g.Min(i => dostuff(i,"Disc")), //not required
                Loc = String.Join<string>(",", from i in g select i.Field<string>("Loc")) //required
            };

dostuff(DataRow i,string field)
{
    try
    {
        return i.Field<string>(field);  
    }
    catch
    {
        return null;
    }
}

So dostuff basically is just checking whether or not that field exists in the dataset, and then I would just need to ignore the non-existant fields when working with the query results, which would not be too difficult. However, it seems like there is probably a better way to do this, but I've had a tough time finding anything via Google about using a dynamic select clause.

Dan Homola
  • 3,819
  • 1
  • 28
  • 43
maembe
  • 1,270
  • 1
  • 13
  • 25
  • 1
    here is your answer http://stackoverflow.com/questions/16516971/linq-dynamic-select – Ehsan Jul 30 '13 at 15:30
  • Why don't you make sure that the `DataTable` always has the same definition? That makes your life so much easier. – Steven Jul 30 '13 at 15:32

1 Answers1

0

You could do it with dynamic type (nb, I did not test so this might have typos.):

var query =dt.AsEnumerable().GroupBy(item => item.Field<string>("ID"))
      .Select(g => {
         dynamic t = new System.Dynamic.ExpandoObject();

         if (g.Table.Columns.Any(c => c.ColumnName == "Status"))
          t.Status = g.Field<string>("Status");

         if (g.Table.Columns.Any(c => c.ColumnName == "Disc"))
          t.Disc = g.Field<string>("Disc");

         t.ID = g.Key;
         t.Loc = String.Join<string>(",",g.Select(i => i.Field<string>("Loc"))); 
         return t;
      }    
Hogan
  • 69,564
  • 10
  • 76
  • 117