sooprise
sooprise

Reputation: 23187

Getting One Field Into An Array?

The following lines of code grabs a handful of rows from a database, and puts the value Table.Id into a list of integers. I imagine there is a way to condense this code into a single line, but I'm not sure how.

var result db.Table.Where(a=>a.Value>0).ToList();
List<int> ids = new List<int>();
foreach(var row in result){
    ids.Add(row.Id);
}

Any help would be appreciated, thanks!

Edit: My title says array, my example has a list, either one is fine. Sorry if there was any confusion.

Upvotes: 0

Views: 94

Answers (3)

BrandonZeider
BrandonZeider

Reputation: 8152

You can also use the List.ForEach Method. So something like:

db.Table.Where(a=>a.Value>0).ToList().ForEach(delegate(Table row) { ids.Add(row.Id); });

Upvotes: 0

Chandu
Chandu

Reputation: 82933

Try this:

var result = db.Table.Where(a=>a.Value>0)
                .Select(a=>a.Id)
                  .ToList(); 

Upvotes: 0

Jimmy
Jimmy

Reputation: 9815

var ids = db.Table.Where(a => a.Value > 0).Select(row => row.Id).ToList();

Should do the trick unless my fu is off

Upvotes: 5

Related Questions