如何使用 Linq 对结果进行排序和排序

发布于 2024-11-15 01:51:18 字数 160 浏览 5 评论 0原文

我有日期时间值(例如 12/01/2010 10:10:222..) 如何按降序顺序仅显示年份?例如,2011、2010、2009、2008 等。我需要仅按字段的年份部分进行分组并返回。我实际上需要返回年份和名称。我需要将该名称用于其他功能,这就是我需要这两个值的原因。

感谢您的帮助...

I have datetime values (e.g. 12/01/2010 10:10:222..) How can I display just the year in desc order? For example, 2011, 2010, 2009, 2008, etc.. I need to group by just the year part of the field and return that. I actually need to return the year and the name. I need to use the name for other functionality, which is why I need the 2 values.

Thanks for any help...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

尴尬癌患者 2024-11-22 01:51:18

目前尚不清楚您的意思,但您可能只是想要这样的内容:

var query = collection.GroupBy(record => record.DateProperty.Year)
                      .OrderBy(group => group.Key);

如果这不是您想要的,请提供更多详细信息 - 最好是一些示例输入和所需的输出。

如果您只想要每个组中的一个条目,并且您很乐意任意选择一个条目来获取名称,并且您只想要年份,那么您可以这样做:

var query = collection.GroupBy(record => record.DateProperty.Year)
                      .Select(g => new { Year = g.Key, Name = g.First().Name })
                      .OrderBy(x => x.Year);

It's not really clear what you mean, but you might just want something like:

var query = collection.GroupBy(record => record.DateProperty.Year)
                      .OrderBy(group => group.Key);

If that's not what you're after, please provide more details - ideally some sample input and desired output.

If you only want one entry from each group and you're happy to take any arbitrary one to get the name, and you only want the year, you could do:

var query = collection.GroupBy(record => record.DateProperty.Year)
                      .Select(g => new { Year = g.Key, Name = g.First().Name })
                      .OrderBy(x => x.Year);
江城子 2024-11-22 01:51:18

我将使用 Distinct 和 OrderByDescending 扩展:

var years = IQueryableObject
                 .Distinct(x => x.Year).OrderByDescending(x => x.Year).ToList();

I would use the Distinct and OrderByDescending extensions:

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