亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從嵌套的并發詞典中刪除項目?

如何從嵌套的并發詞典中刪除項目?

C#
慕田峪4524236 2022-09-04 16:54:27
我試圖做的是讓群聊的在線成員留在記憶中。我定義了一個靜態嵌套字典,如下所示:private static ConcurrentDictionary<string, ConcurrentDictionary<string, ChatMember>> onlineGroupsMembers = new ConcurrentDictionary<string, ConcurrentDictionary<string, ChatMember>>();然后,當新成員到達時,我添加它:        onlineGroupsMembers.AddOrUpdate            (chatKey,            (k) => // add new            {                var dic = new ConcurrentDictionary<string, ChatMember>();                dic[chatMember.Id] = chatMember;                return dic;            },            (k, value) => // update            {                value[chatMember.Id] = chatMember;                return value;            });現在的問題是,如何從內部字典中刪除成員?還如何在外部字典中刪除空的字典?并發字典有 TryRemove,但它沒有幫助,檢查 ContainsKey 然后刪除它不是原子的。謝謝。
查看完整描述

1 回答

?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

要從組中刪除 a,您需要獲取該組的...ChatMemberConcurrentDictionary<>

var groupDictionary = onlineGroupsMembers["groupID"];

...或。。。

var groupDictionary = onlineGroupsMembers.TryGetValue("groupID", out ConcurrentDictionary<string, ChatMember> group);

然后,您將嘗試刪除該成員...groupDictionary

var wasMemberRemoved = groupDictionary.TryRemove("memberID", out ChatMember removedMember);

要從中完全刪除組,請直接在該字典上調用...onlineGroupsMembersTryRemove

 var wasGroupRemoved = onlineGroupsMembers.TryRemove("groupID", out ConcurrentDictionary<string, ChatMember> removedGroup);

實現此目的的一種不那么麻煩的方法可能是使用兩個未嵌套的字典。人們會從組ID映射到類似ConcurrentBag<>或并發HashSet<>(如果存在)的東西。ChatMember

ConcurrentDictionary<string, ConcurrentBag<ChatMember>> groupIdToMembers;

...或從組 ID 到其成員 ID...

ConcurrentDictionary<string, ConcurrentBag<string>> groupIdToMemberIds;

請注意,允許重復值。ConcurrentBag<>

在后一種情況下,如果您想要一種快速獲取給定成員ID的方法,則可以使用另一個字典來獲取...ChatMember

ConcurrentDictionary<string, ChatMember> memberIdToMember;


查看完整回答
反對 回復 2022-09-04
  • 1 回答
  • 0 關注
  • 97 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號