[英]Simple Linq question: How to select more than one column?
my code is: 我的代码是:
List<Benutzer> users = (from a in dc.Benutzer
select a).ToList();
I need this code but I only want to select 3 of the 20 Columns in the "Benutzer"-Table. 我需要这个代码,但我只想在“Benutzer”-Table中选择20个列中的3个。 What is the syntax for that?
那是什么语法?
Here's a query expression: 这是一个查询表达式:
var users = (from a in dc.Benutzer
select new { a.Name, a.Age, a.Occupation }).ToList();
Or in dot notation: 或者用点符号表示:
var users = dc.Benutzer.Select(a => new { a.Name, a.Age, a.Occupation })
.ToList();
Note that this returns a list of an anonymous type rather than instances of Benutzer
. 请注意,这将返回匿名类型的列表,而不是
Benutzer
实例。 Personally I prefer this approach over creating a list of partially populated instances, as then anyone dealing with the partial instances needs to check whether they came from to find out what will really be there. 我个人更喜欢这种方法而不是创建一个部分填充的实例列表,因为任何处理部分实例的人都需要检查它们是否来自于找出实际存在的内容。
EDIT: If you really want to build instances of Benutzer
, and LINQ isn't letting you do so in a query (I'm not sure why) you could always do: 编辑:如果你真的想构建
Benutzer
实例,并且LINQ不允许你在查询中这样做(我不知道为什么)你可以随时做:
List<Benutzer> users = dc.Benutzer
.Select(a => new { a.Name, a.Age, a.Occupation })
.AsEnumerable() // Forces the rest of the query to execute locally
.Select(x => new Benutzer { Name = x.Name, Age = x.Age,
Occupation = x.Occupation })
.ToList();
ie use the anonymous type just as a DTO. 即使用匿名类型作为DTO。 Note that the returned
Benutzer
objects won't be associated with a context though. 请注意,返回的
Benutzer
对象不会与上下文关联。
List<Benutzer> users = (from a in dc.Benutzer
select new Benutzer{
myCol= a.myCol,
myCol2 = a.myCol2
}).ToList();
I think that's what you want if you want to make the same kind of list. 如果你想制作同样的清单,我认为这就是你想要的。 But that assumes that the properties you are setting have public setters.
但是,假设您设置的属性具有公共设置器。
try: 尝试:
var list = (from a in dc.Benutzer select new {a.Col1, a.Col2, a.Col3}).ToList();
but now you have list of anonymous object not of Benutzer objects. 但现在你有匿名对象的列表而不是Benutzer对象的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.