5

Is it possible, and if so how, to loop though the results of a LINQ query?

Something like this:

var results= from a in dt.AsEnumerable()
                    where a.Field<int>("id") == i 
                    select new 
                    {
                       id= a.Field<int>("id"),
                       a= a.Field<double>("a"),
                       b = a.Field<double>("b")
                    };

IEnumerable<string> colNames = results.First().GetType().GetProperties()
                                                        .Select(p => p.Name);

string[] columns = colNames.ToArray();

int i = 0;
foreach (var row in results)
{
    for (int i = 0; i < columns.Count(); i++)
    {
        string foobar = (string)row[columns[i]];
        i++;
    }
}

Essentially, i want to replicate the following sort of functionality:

DataRow dr = new DataRow();
string foobar = dr[columns[i];

Thanks all in advance.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
CatchingMonkey
  • 1,391
  • 2
  • 14
  • 36

3 Answers3

4

If you have the option of changing your original LINQ statement to produce a data structure that allows you to do what you're looking for, I'd definitely suggest that.

If not, you'll need to use reflection to look up the properties of your anonymous type by their name, and then get the values of those properties by reflection:

    PropertyInfo[] columns = results.First().GetType().GetProperties();
    ...
            string foobar = columns[i].GetValue(row, null);
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • I havent really got the option no. However, i have used a bit of reflection to get the properties, i just dont know what to do with them now! – CatchingMonkey Oct 27 '11 at 13:51
3
Action<string> processColumName = (cname) => 
                           { 
                              // do anything you want with a column name
                              string foo = (string) Row[cname]; 
                           };

results.First()
        .GetType()
        .GetProperties()
        .Select(p => p.Name)
        .ToList().ForEach(processColumName);
sll
  • 61,540
  • 22
  • 104
  • 156
1

Well my answer actually is based on someone's else answer (I will be leaving a link below) with sligh changes: stovroz

So here is the code:

foreach(var item in db.Products) {
   System.Reflection.PropertyInfo[] fields = Product.GetType().GetProperties(); 
   foreach(var f in fields) {
      Console.WriteLine(f.Name + ": " + f.GetValue(item));
   }  
} 

Actually I was looking for such a solution to reach dynamic LINQ usage and this guy saved my day. Huge thanks to him!

NekoMisaki
  • 101
  • 1
  • 6