Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Many Fields From a Table using Linq and Lambda Expressions

I have a DataContext (db) that can access the tables in my SQL Express database, from which I would like to extract only three of the multiple fields in the tblItem table:

// this does not work - what is the correct way to do it?  
var items = db.tblItems.Select(i => i.id && i.name && i.totalAmount);

The intention is to spit these out into a csv file (comma separated). Is a var the best way to do this?

like image 529
Jimbo Avatar asked Dec 02 '22 04:12

Jimbo


2 Answers

You will have to use an anomynous object for this:

var items = db.tblItems.Select(i => 
            new { 
                  ID = i.id, 
                  Name = i.name, 
                  TotalAmount = i.totalAmount
                });

You can iterate over items like over any other collection:

foreach(var item in items)
{
  //do stuff
}
like image 113
Femaref Avatar answered Dec 05 '22 07:12

Femaref


If by "a var" you mean an anonymous type, then probably:

var items = db.tblItems.Select(i => new { i.id, i.name, i.totalAmount });
like image 40
Jon Skeet Avatar answered Dec 05 '22 07:12

Jon Skeet