Selecting Many Fields From a Table using Linq and Lambda Expressions

后端 未结 3 2036
青春惊慌失措
青春惊慌失措 2021-01-19 13:46

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 tbl

相关标签:
3条回答
  • 2021-01-19 14:11

    Yes, either use an anonymous type like so

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

    Or if you have a class use it instead.

     var items = 
        db.tblItems.Select(i => 
        new ItemsClass() //Or whatever
        {
         Id = i.id,
         Name = i.name,
         TotalAmount = i.totalAmount,
        });
    
    0 讨论(0)
  • 2021-01-19 14:14

    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
    }
    
    0 讨论(0)
  • 2021-01-19 14:22

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

    var items = db.tblItems.Select(i => new { i.id, i.name, i.totalAmount });
    
    0 讨论(0)
提交回复
热议问题