使用 LINQ 如何在 select 运算符的结果中返回字符串常量

发布于 2024-09-24 20:48:01 字数 750 浏览 0 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半仙 2024-10-01 20:48:01

您可以通过添加 PropertyName = 来指定匿名类型的其他成员,因此,如果您想添加具有某个常量值的属性 Genre,您可以编写:

new { t.Name, t.Rating, t.AverageRating, 
      t.ShortSynopsis, Genre = "Action & Adventure" }

Genre 的值可能与查询中的 genre 变量或属性 g.Name 相同,因此您可以使用此属性(而不是字符串文字):

new { t.Name, t.Rating, t.AverageRating, 
      t.ShortSynopsis, Genre = g.Name } // Or 'Genre = genre'

值得注意的是,如果你只是在匿名类型的构造中使用一些属性名称(例如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 property Genre with some constant value, you can write:

new { t.Name, t.Rating, t.AverageRating, 
      t.ShortSynopsis, Genre = "Action & Adventure" }

The value of genre will be probably the same as the genre variable or the property g.Name in your query, so you could use this property (instead of string literal):

new { t.Name, t.Rating, t.AverageRating, 
      t.ShortSynopsis, Genre = g.Name } // Or 'Genre = genre'

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 writing Name = t.Name (the compiler copies the property name automatically).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文