From 46b9d1b09dcc75e29baa462517b9a6ce058adc12 Mon Sep 17 00:00:00 2001 From: Gadfly Date: Thu, 16 May 2024 16:33:34 +0800 Subject: [PATCH] refactor: Simplify FindOrAdd method by using ConcurrentDictionary's GetOrAdd --- src/Models/User.cs | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/src/Models/User.cs b/src/Models/User.cs index ba1bebd6..5a93e135 100644 --- a/src/Models/User.cs +++ b/src/Models/User.cs @@ -25,20 +25,14 @@ namespace SourceGit.Models public static User FindOrAdd(string data) { - if (_caches.TryGetValue(data, out var value)) + return _caches.GetOrAdd(data, key => { - return value; - } - else - { - var nameEndIdx = data.IndexOf('<', System.StringComparison.Ordinal); - var name = nameEndIdx >= 2 ? data.Substring(0, nameEndIdx - 1) : string.Empty; - var email = data.Substring(nameEndIdx + 1); + var nameEndIdx = key.IndexOf('<', System.StringComparison.Ordinal); + var name = nameEndIdx >= 2 ? key.Substring(0, nameEndIdx - 1) : string.Empty; + var email = key.Substring(nameEndIdx + 1); - User user = new User() { Name = name, Email = email }; - _caches.TryAdd(data, user); - return user; - } + return new User() { Name = name, Email = email }; + }); } private static ConcurrentDictionary _caches = new ConcurrentDictionary();