GroupBy 然后采用 LINQ to Entities?

发布于 2024-10-26 05:16:51 字数 689 浏览 2 评论 0原文

假设我有以下项目:

ID      Category        Name

1       Fruit           Banana
2       Car             Mescedes
3       Fruit           Blackberry
4       Fruit           Mango
5       Car             Lexus
6       Fruit           Melon
7       Car             BMW
8       Car             Toyota

我想将它们分组为 Category 并仅获取每个 Category 的前 3 个项目。是否可以?

我期望的输出:

ID        Category        Name

1        Fruit           Banana
3        Fruit           Blackberry
4        Fruit           Mango
2        Car             Mescedes
5        Car             Lexus
7        Car             BMW

任何帮助将不胜感激!

Let's say I have the following items:

ID      Category        Name

1       Fruit           Banana
2       Car             Mescedes
3       Fruit           Blackberry
4       Fruit           Mango
5       Car             Lexus
6       Fruit           Melon
7       Car             BMW
8       Car             Toyota

I want to group them into Category and take only the first 3 items of each Category. Is it possible?

I expected the output:

ID        Category        Name

1        Fruit           Banana
3        Fruit           Blackberry
4        Fruit           Mango
2        Car             Mescedes
5        Car             Lexus
7        Car             BMW

Any helps would be appreciated!

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

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

发布评论

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

评论(2

ヤ经典坏疍 2024-11-02 05:16:51

来自头部且未测试:

from c in categoryList
group by c.Category into g
let fewItems = g.Take(3).ToList()
return new { Category = g.Key, Items = fewItems }

From head and not tested:

from c in categoryList
group by c.Category into g
let fewItems = g.Take(3).ToList()
return new { Category = g.Key, Items = fewItems }
乄_柒ぐ汐 2024-11-02 05:16:51

假设您的列表集合被命名为categoryList..

实现您想要的结果的linq 查询是:

categoryList.GroupBy(c=>c.Category).Take(3)

Lets say you list collection is named as categoryList..

The linq queries to achive what you want is:

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