0

How do I loop through column names in Linq to SQL

var foo = (from f in db.bar select f).ToList()

What I want to do is loop through each column name, i.e.

    foreach bar d in foo
{
    foreach column in d
      {<do something>}
}

Is that possible?

Joe Stellato
  • 558
  • 9
  • 31

3 Answers3

3

Here's a method that returns a LINQ-to-sql query as an enumerable of dictionaries:

IEnumerable<IDictionary<string, object>> GetValues<T>(DataContext context,
                                                         IQueryable<T> query)
    where T : class
{
    var propertyInfos = typeof(T).GetProperties().ToDictionary (pi => pi.Name);
    foreach(var entity in context.GetTable<T>())
    {
        yield return (context.Mapping.GetTable(typeof(T)).RowType.DataMembers
           .Where(dm => !dm.IsAssociation).Select (dm => dm.Name)
        .Select(name => new { name, 
                              value = propertyInfos[name].GetValue(entity, null)
                            })
        .ToDictionary (x => x.name, y => y.value));
    }
}

You get the column names and the values from the dictionaries:

var foo = (from f in db.bar select f);
foreach(var dictionary in GetValues(db, foo))
{
    // do something with dictionary keys and/or values
}
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
2

If you haven't extended your mapped model with other fields, or don't mind iterating over them too, you could use:

var fields = typeof(Product).GetFields();
foreach(var item in db.Products)  
{  
    foreach(var f in fields)  
    {  
        Console.WriteLine(f.Name + ": " + f.GetValue(item));
    }  
 } 
stovroz
  • 6,835
  • 2
  • 48
  • 59
-1

Here is an example of what I think you want, if this isn't good enough to get you started, please explain what you need in more detail.

var myTable = new DataTable();
myTable.Columns.Add("Column One");
myTable.Columns.Add("Column Two");

var newRow = myTable.NewRow();
newRow[0] = 11111;
newRow[1] = 22222;
myTable.Rows.Add(newRow);

var newRow2 = myTable.NewRow();
newRow2 [0] = 33333;
newRow2 [1] = 44444;
myTable.Rows.Add(newRow2);


foreach (var row in myTable.AsEnumerable())
{
    foreach (DataColumn column in myTable.Columns)
    {
        Console.WriteLine("Column {0}, Row {1}, Value {2}", column.ColumnName, myTable.Rows.IndexOf(row), row[column]);
    }
}
Faraday
  • 2,904
  • 3
  • 23
  • 46
  • I think the problem here, is that I'm not using datatables but linq to sql classes – Joe Stellato Jun 04 '14 at 13:18
  • @JStellato - Mock something up for me to use and I'll write you some code, but I'm don't use L2S as it's slow, so I don't have anything ready to test with. Like I said, write a quick mock up and I'll make it work :) – Faraday Jun 04 '14 at 13:25
  • @Vijay If you aren't at all familiar with the tools/paradigm that the question is based on then why are you answering it in the first place? – Servy Jun 04 '14 at 14:10
  • @Servy - The initial question didn't explain what anything was, hence the first few questions we asked. I wrote this before they replied as I took a guess as to what they meant. My offer to code something up was because no one else had answered and it was meant to be a nice offer to the OP, if they needed the help I was willing. – Faraday Jun 04 '14 at 18:06
  • The question itself, which hasn't been edited, says that it's a LINQ to SQL question right in it, and the code is obviously LINQ to SQl code and not a `DataTable`. No clarifications on that point were needed. – Servy Jun 04 '14 at 18:08
  • All I can do is say sorry that both I and `D Stanley` had questions. My answer was just meant to point the OP in the right direction and I offered more help. Exactly what (other than answering before the OP cleared up the classes being used) did I do wrong exactly? – Faraday Jun 04 '14 at 18:24