如何在 EF 中将 GroupBy 与 Linq 的方法语法结合使用?



我有以下查询:

var chat_AppUsers = _context.Chat_AppUsers;
var chats = _context.Chats;
var chat_lists = chat_AppUsers.Join(chats,
ca => ca.ChatId,
c => c.ChatId,
(ca, c) => new
{
ChatId = ca.ChatId,
ChatType = c.ChatType,
chat_AppUsers = c.chat_AppUsers
}
).ToList();
var grouped_list = chat_lists
.GroupBy(c => c.ChatId);

基本上,我想要ChatId与用户的所有聊天列表,如:

"result": [
{
"chatId": "alice_bob_id_1",
"chat_AppUsers": [
{
"chat_AppUserId": "Chat_AppUserId_1",
"chatId": "alice_bob_id_1",
"chat": null,
"appUserId": "bob_id",
"appUser": null
},
{
"chat_AppUserId": "Chat_AppUserId_2",
"chatId": "alice_bob_id_1",
"chat": null,
"appUserId": "alice_id",
"appUser": null
}
]
},
]

GroupBy不按alice_bob_id_1的唯一ChatId分组,并且由于我在Chat_AppUsers中有两个用户,因此我得到了下面重复的结果:

"result": [
{
"chatId": "alice_bob_id_1",
"chat_AppUsers": [
{
"chat_AppUserId": "Chat_AppUserId_1",
"chatId": "alice_bob_id_1",
"chat": null,
"appUserId": "bob_id",
"appUser": null
},
{
"chat_AppUserId": "Chat_AppUserId_2",
"chatId": "alice_bob_id_1",
"chat": null,
"appUserId": "alice_id",
"appUser": null
}
]
},
{
"chatId": "alice_bob_id_1",
"chat_AppUsers": [
{
"chat_AppUserId": "Chat_AppUserId_1",
"chatId": "alice_bob_id_1",
"chat": null,
"appUserId": "bob_id",
"appUser": null
},
{
"chat_AppUserId": "Chat_AppUserId_2",
"chatId": "alice_bob_id_1",
"chat": null,
"appUserId": "alice_id",
"appUser": null
}
]
},
]

我是Linq的初学者,并且无法在任何地方找到使用JoinGroupBy使用方法语法的例子。

谢谢,非常感谢,

linq的方法语法很难理解我更喜欢使用查询语法

var query = from chatAppUser in _context.Chat_AppUser
join chat in _context.Chat
on chatAppUser.ChatId equals chat.Id
select new
{
ChatId = chat.Id,
Chat_AppUser = chat.Chat_AppUsers
};

,但也有一个更简单的方法来连接两个表

var query = _context.Chat.Include(i => i.Chat_AppUser).ToList();

对于你的问题…

Linq中的GroupBy元素是igrouing的一个关键值IEnumerable

GroupBy操作符根据某个键值返回给定集合中的一组元素。每一组由IGrouping<TKey,>对象。从tutorialsTeacher

我希望这个链接能帮到你

我认为您可以通过先将chat_AppUsersChatId分组,然后将分组结果与chats:

var grouped_list = chatAppUsers
.GroupBy(appUser => appUser.ChatId)
.Join(chats,
appUserGroup => appUserGroup.Key,
chat => chat.ChatId,
(appUserGroup, chat) => new {
ChatId = chat.ChatId,
ChatType = chat.ChatType,
Chat_AppUsers = appUserGroup
})
.ToList();
以您的示例为例,chat_AppUsers的简化版本可能如下所示:
chat_AppUsers:
{
ChatId: "alice_bob_id_1",
AppUserId: "bob_id"
},
{
ChatId: "alice_bob_id_1",
AppUserId: "alice_id"
}

.GroupBy()操作

chatAppUsers.GroupBy(appUser => appUser.ChatId)

将按ChatId对应用程序用户进行分组。.GroupBy()操作的结果可以(在枚举之后,例如在调用.ToList()之后)显示为

[0]
Key: "alice_bob_id_1"
[0]
ChatId: "alice_bob_id_1"
AppUserId: "bob_id"
[1]
ChatId: "alice_bob_id_1"
AppUserId: "alice_id"

当我们用chats加入这个分组时,基于分组的Key,应用程序用户已经正确地分组到他们各自的聊天。

示例在这里。

相关内容

  • 没有找到相关文章

最新更新