Lewis Cianci
Lewis Cianci

Reputation: 1065

How do I iterate through each column of data in a LINQ to SQL query?

Imagine my LINQ to SQL query is this:

var query = (from q in db.GetTable<potato>()
            where q.ID == dbID
            select q).FirstOrDefault();

How would I iterate horizontally instead of vertically?. So there's just the one row, I want to iterate through each data item in a column per column basis, instead of row by row. There's quite a few properties so I'd just like to iterate instead of writing them all manually.

Upvotes: 0

Views: 1190

Answers (2)

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

If data you want is Property:

var values = typeof(potato)
    .GetProperties()
    .Select(p=>p.GetValue(query,null))
    .ToArray();

If data is Field:

var values = typeof(potato)
    .GetFields()
    .Select(p=>p.GetValue(query))
    .ToArray();

If some property must be returned you can filter PropertyInfoes or FieldInfoes like below:

typeof(potato)
    .GetFields()
    .Where(p=>...labla...)
    .Select...

Upvotes: 1

Lali
Lali

Reputation: 2866

You can get this through reflection

foreach (PropertyInfo propertyInfo in potato.GetType().GetProperties())
{
    if (propertyInfo.CanRead)
    {
          string val= propertyInfo.GetValue(potato, null).ToString();
    }
}

Upvotes: 1

Related Questions