tags:

views:

3394

answers:

4

Consider this:

var query = from r in this._db.Recipes
            where r.RecipesID == recipeID
            select new { r.RecipesID, r.RecipesName };

How would i get individual columns in my query object without using a for-loop?

Basicly: how do I translate DataTable.Rows[0]["ColumnName"] into Linq syntax?

A: 

Sorry, misunderstood your question. As others are saying, you can use ToList() to get a List back. An alternative if all you need is the first one, just use:


query.First().ColumnName

or if you want to avoid an exception on empty list:


var obj = query.FirstOrDefault();
if (obj != null)
   obj.ColumnName;


Original Answer (so the comment makes sense):

Use Linq to Datasets. Basically would be something like:


var query = from r in yourTable.AsEnumerable()
select r.Field<string>("ColumnName");
Chris Shaffer
In my mind, that kind of defeats the purpose of Linq.
roosteronacid
+2  A: 

It's really unclear what you are looking for, as your two samples are compatible.

As close as I can figure, what you want is:

var rows = query.ToList();
string name = rows[0].RecipesName;
James Curran
Exactly what I wanted :)
roosteronacid
+1  A: 
string name = this._db.Recipes.Single(r => r.RecipesID == recipeID).RecipesName;
Richard Poole
A: 

This is the way to go about it:

DataContext dc = new DataContext();

var recipe = (from r in dc.Recipes 
              where r.RecipesID == 1
              select r).FirstOrDefault();

if (recipe != null)
{
    id = recipe.RecipesID;
    name = recipe.RecipesName;
}
roosteronacid
You can use either Single() or First(). The difference is that Single() will throw an exception if your LINQ query returns multiple rows.
Kyralessa