使用Linq和Lambda表达式从表中选择多个字段 [英] Selecting Many Fields From a Table using Linq and Lambda Expressions
本文介绍了使用Linq和Lambda表达式从表中选择多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个DataContext
(db),可以访问我的SQL Express数据库中的表,我只想从中提取tblItem表中多个字段中的三个:
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);
目的是将它们吐到一个csv文件中(以逗号分隔). var
是执行此操作的最佳方法吗?
The intention is to spit these out into a csv file (comma separated). Is a var
the best way to do this?
推荐答案
为此,您将必须使用一个专有对象:
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
});
您可以像遍历任何其他集合一样遍历items
:
You can iterate over items
like over any other collection:
foreach(var item in items)
{
//do stuff
}
这篇关于使用Linq和Lambda表达式从表中选择多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文