我有以下查询:
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的初学者,并且无法在任何地方找到使用Join
和GroupBy
使用方法语法的例子。
谢谢,非常感谢,
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_AppUsers
按ChatId
分组,然后将分组结果与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
,应用程序用户已经正确地分组到他们各自的聊天。
示例在这里。