使用 LINQ 如何在 select 运算符的结果中返回字符串常量
在 LinqPad 中,我有以下查询语句...
var genre = "Anime & Animation";
var minRating = 3.0;
var topNum = 30;
var query =
(from g in Genres
from t in g.Titles
where g.Name==genre
&& t.Instant.Available==true
&& t.AverageRating >= minRating
orderby t.AverageRating descending
select new {t.Name, t.Rating, t.AverageRating, t.ShortSynopsis}).Take(topNum);
query.Dump(string.Format("Top {0} {1} Instant Watch Movies with a {2:0.0} minimum average rating sorted by average rating in descending order.",topNum,genre,minRating));
我想返回结果集中的流派字符串变量。
另一种提问方式是,使用 TSQL,我会执行“SELECT field1, field2, 'Action & Adventure' 作为 MyTitles 中的流派”。那么如何在 Linq 中做到这一点呢?
赛斯
In LinqPad I have the following query statements...
var genre = "Anime & Animation";
var minRating = 3.0;
var topNum = 30;
var query =
(from g in Genres
from t in g.Titles
where g.Name==genre
&& t.Instant.Available==true
&& t.AverageRating >= minRating
orderby t.AverageRating descending
select new {t.Name, t.Rating, t.AverageRating, t.ShortSynopsis}).Take(topNum);
query.Dump(string.Format("Top {0} {1} Instant Watch Movies with a {2:0.0} minimum average rating sorted by average rating in descending order.",topNum,genre,minRating));
I want to return the genre string variable in the result set.
Another way to ask, with TSQL I would do "SELECT field1, field2, 'Action & Adventure' as genre from MyTitles". So how do you do that in Linq.
Seth
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过添加
PropertyName =
来指定匿名类型的其他成员,因此,如果您想添加具有某个常量值的属性Genre
,您可以编写:Genre 的值可能与查询中的
genre
变量或属性g.Name
相同,因此您可以使用此属性(而不是字符串文字):值得注意的是,如果你只是在匿名类型的构造中使用一些属性名称(例如
t.Name
),那么它只是编写Name = t.Name
的快捷方式> (编译器自动复制属性名称)。You can specify additional members of the anonymous type by adding
PropertyName = <value>
, so if you want to add a propertyGenre
with some constant value, you can write:The value of genre will be probably the same as the
genre
variable or the propertyg.Name
in your query, so you could use this property (instead of string literal):It is worth noting that if you just use some property name in the construction of anonymous type (e.g.
t.Name
), it is just a shortcut for writingName = t.Name
(the compiler copies the property name automatically).