Skip to content

Commit f51475a

Browse files
committed
Dictionary.ContainsKey replaced with TryGetValue/TryAdd/TryRemove
1 parent 06d5cf5 commit f51475a

110 files changed

Lines changed: 624 additions & 1259 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Orm/Xtensive.Orm.PostgreSql/Sql.Drivers.PostgreSql/v8_0/Extractor.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -718,14 +718,14 @@ protected virtual void ReadColumnData(DbDataReader dataReader, ExtractionContext
718718
var columnOwnerId = Convert.ToInt64(dataReader["attrelid"]);
719719
var columnId = Convert.ToInt64(dataReader["attnum"]);
720720
var columnName = dataReader["attname"].ToString();
721-
if (tableMap.ContainsKey(columnOwnerId)) {
722-
var table = tableMap[columnOwnerId];
721+
if (tableMap.TryGetValue(columnOwnerId, out var table)) {
723722
var col = table.CreateColumn(columnName);
724-
if (!tableColumns.ContainsKey(columnOwnerId)) {
725-
tableColumns.Add(columnOwnerId, new Dictionary<long, TableColumn>());
723+
if (tableColumns.TryGetValue(columnId, out var column)) {
724+
tableColumns.Add(columnId, new Dictionary<long, TableColumn>());
725+
}
726+
else {
727+
column.Add(columnId, col);
726728
}
727-
728-
tableColumns[columnOwnerId].Add(columnId, col);
729729

730730
var columnTypeName = dataReader["typname"].ToString();
731731
var columnTypeSpecificData = Convert.ToInt32(dataReader["atttypmod"]);

Orm/Xtensive.Orm/Modelling/Actions/ActionSequence.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ public void Add(NodeAction action)
5151
var last = actions[lastIndex] as PropertyChangeAction;
5252
if (last!=null && ca.Path==last.Path) {
5353
foreach (var pair in last.Properties) {
54-
if (!ca.Properties.ContainsKey(pair.Key))
55-
ca.Properties.Add(pair.Key, pair.Value);
54+
_ = ca.Properties.TryAdd(pair.Key, pair.Value);
5655
}
5756
actions.RemoveAt(lastIndex);
5857
}

Orm/Xtensive.Orm/Modelling/Actions/GroupingNodeAction.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,7 @@ public void Add(NodeAction action)
5656
var last = actions[lastIndex] as PropertyChangeAction;
5757
if (last!=null && ca.Path==last.Path) {
5858
foreach (var pair in last.Properties) {
59-
if (!ca.Properties.ContainsKey(pair.Key))
60-
ca.Properties.Add(pair.Key, pair.Value);
59+
_ = ca.Properties.TryAdd(pair.Key, pair.Value);
6160
}
6261
actions.RemoveAt(lastIndex);
6362
}

Orm/Xtensive.Orm/Modelling/Comparison/Hints/HintSet.cs

Lines changed: 38 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -77,31 +77,25 @@ public void Add(Hint hint)
7777
var nodes = new List<Node>();
7878
foreach (var target in targets) {
7979
Node node;
80-
if (target.Model==ModelType.Source)
80+
if (target.Model == ModelType.Source)
8181
node = (Node) SourceModel.Resolve(target.Path, true);
8282
else
8383
node = (Node) TargetModel.Resolve(target.Path, true);
8484
nodes.Add(node);
85-
86-
if (!hintMap.ContainsKey(node))
87-
hintMap.Add(node, new Dictionary<Type, object>());
88-
var nodeHintMap = hintMap[node];
85+
86+
var nodeHintMap = GetNodeHints(node);
8987
var hintType = hint.GetType();
90-
91-
if (!nodeHintMap.ContainsKey(hintType))
92-
nodeHintMap.Add(hintType, null);
93-
94-
var hintOrList = nodeHintMap[hintType];
95-
if (hintOrList==null)
96-
nodeHintMap[hintType] = hint;
97-
else {
98-
var list = hintOrList as List<Hint>;
99-
if (list==null) {
100-
var oldHint = (Hint) hintOrList;
101-
nodeHintMap[hintType] = new List<Hint>(new[] {oldHint, hint});
102-
}
103-
else
88+
89+
if (nodeHintMap.TryGetValue(hintType, out var hintOrList)) {
90+
if (hintOrList is List<Hint> list) {
10491
list.Add(hint);
92+
}
93+
else {
94+
nodeHintMap[hintType] = new List<Hint>(new[] { (Hint) hintOrList, hint });
95+
}
96+
}
97+
else {
98+
nodeHintMap.Add(hintType, hint);
10599
}
106100
}
107101
}
@@ -126,46 +120,20 @@ public void Clear()
126120

127121
/// <inheritdoc/>
128122
/// <exception cref="InvalidOperationException">Multiple hints found.</exception>
129-
public THint GetHint<THint>(Node node)
130-
where THint : Hint
131-
{
132-
ArgumentValidator.EnsureArgumentNotNull(node, "node");
133-
134-
if (!hintMap.ContainsKey(node))
135-
hintMap.Add(node, new Dictionary<Type, object>());
136-
var nodeHintMap = hintMap.GetValueOrDefault(node);
137-
if (nodeHintMap==null)
138-
return null;
139-
var hintType = typeof(THint);
140-
var hintOrList = nodeHintMap.GetValueOrDefault(hintType);
141-
if (hintOrList==null)
142-
return null;
143-
var hint = hintOrList as THint;
144-
if (hint!=null)
145-
return hint;
146-
throw new InvalidOperationException(Strings.ExMultipleHintsFound);
147-
}
123+
public THint GetHint<THint>(Node node) where THint : Hint =>
124+
GetNodeHints(node).GetValueOrDefault(typeof(THint)) switch {
125+
null => null,
126+
THint hint => hint,
127+
_ => throw new InvalidOperationException(Strings.ExMultipleHintsFound)
128+
};
148129

149130
/// <inheritdoc/>
150-
public THint[] GetHints<THint>(Node node)
151-
where THint : Hint
152-
{
153-
ArgumentValidator.EnsureArgumentNotNull(node, "node");
154-
155-
if (!hintMap.ContainsKey(node))
156-
hintMap.Add(node, new Dictionary<Type, object>());
157-
var nodeHintMap = hintMap.GetValueOrDefault(node);
158-
if (nodeHintMap==null)
159-
return ArrayUtils<THint>.EmptyArray;
160-
var hintType = typeof (THint);
161-
var hintOrList = nodeHintMap.GetValueOrDefault(hintType);
162-
if (hintOrList==null)
163-
return ArrayUtils<THint>.EmptyArray;
164-
var hint = hintOrList as THint;
165-
if (hint!=null)
166-
return new[] {hint};
167-
return ((List<Hint>) hintOrList).Cast<THint>().ToArray();
168-
}
131+
public THint[] GetHints<THint>(Node node) where THint : Hint =>
132+
GetNodeHints(node).GetValueOrDefault(typeof(THint)) switch {
133+
null => Array.Empty<THint>(),
134+
THint hint => new[] { hint },
135+
var list => ((List<Hint>) list).Cast<THint>().ToArray()
136+
};
169137

170138
/// <summary>
171139
/// Determines whether there are any hints associated with the specified.
@@ -175,29 +143,10 @@ public THint[] GetHints<THint>(Node node)
175143
/// <see langword="true"/> if the specified node has associated hints;
176144
/// otherwise, <see langword="false"/>.
177145
/// </returns>
178-
public bool HasHints(Node node)
179-
{
180-
ArgumentValidator.EnsureArgumentNotNull(node, "node");
146+
public bool HasHints(Node node) => GetNodeHints(node).Count > 0;
181147

182-
if (!hintMap.ContainsKey(node))
183-
hintMap.Add(node, new Dictionary<Type, object>());
184-
var nodeHintMap = hintMap.GetValueOrDefault(node);
185-
if (nodeHintMap==null)
186-
return false;
187-
188-
return nodeHintMap.Values.Count > 0;
189-
}
190-
191-
public bool HasHints<THint>(Node node)
192-
where THint : Hint
193-
{
194-
ArgumentValidator.EnsureArgumentNotNull(node, "node");
195-
196-
if (!hintMap.TryGetValue(node, out var nodeHintMap)) {
197-
hintMap.Add(node, nodeHintMap = new Dictionary<Type, object>());
198-
}
199-
return nodeHintMap.ContainsKey(typeof(THint));
200-
}
148+
public bool HasHints<THint>(Node node) where THint : Hint =>
149+
GetNodeHints(node).ContainsKey(typeof(THint));
201150

202151
#region IEnumerable<...> methods
203152

@@ -215,6 +164,16 @@ IEnumerator IEnumerable.GetEnumerator()
215164

216165
#endregion
217166

167+
private Dictionary<Type, object> GetNodeHints(Node node)
168+
{
169+
ArgumentValidator.EnsureArgumentNotNull(node, "node");
170+
171+
if (!hintMap.TryGetValue(node, out var nodeHintMap)) {
172+
hintMap.Add(node, nodeHintMap = new Dictionary<Type, object>());
173+
}
174+
return nodeHintMap;
175+
}
176+
218177
#region ILockable methods
219178

220179
/// <inheritdoc/>

Orm/Xtensive.Orm/Modelling/NodeCollection.cs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -228,22 +228,22 @@ public override void Lock(bool recursive)
228228
internal void Add(Node node)
229229
{
230230
this.EnsureNotLocked();
231-
if (node.Index!=list.Count)
231+
if (node.Index != list.Count)
232232
throw Exceptions.InternalError("Wrong NodeCollection.Add arguments: node.Index!=list.Count!", CoreLog.Instance);
233233
string name = node.Name;
234-
if (nameIndex.ContainsKey(name))
235-
throw Exceptions.InternalError("Wrong NodeCollection.Add arguments: nameIndex[node.Name]!=null!", CoreLog.Instance);
236234
int count = list.Count;
235+
if (!nameIndex.TryAdd(name, node)) {
236+
throw Exceptions.InternalError("Wrong NodeCollection.Add arguments: nameIndex[node.Name]!=null!", CoreLog.Instance);
237+
}
237238
try {
238239
list.Add(node);
239-
nameIndex.Add(name, node);
240240
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
241241
NotifyCollectionChangedAction.Add, node.Index));
242242
}
243243
catch {
244-
if (list.Count>count)
244+
if (list.Count > count)
245245
list.RemoveAt(count);
246-
if (nameIndex.Count>count)
246+
if (nameIndex.Count > count)
247247
nameIndex.Remove(name);
248248
throw;
249249
}
@@ -259,8 +259,7 @@ internal void Remove(Node node)
259259
string name = node.Name;
260260
try {
261261
list.RemoveAt(index);
262-
if (nameIndex.ContainsKey(name))
263-
nameIndex.Remove(name);
262+
nameIndex.Remove(name);
264263
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
265264
NotifyCollectionChangedAction.Remove, index));
266265
}
@@ -316,21 +315,18 @@ internal void RemoveName(Node node)
316315
internal void AddName(Node node)
317316
{
318317
this.EnsureNotLocked();
319-
string name = node.Name;
320-
if (nameIndex.ContainsKey(name))
318+
if (!nameIndex.TryAdd(node.Name, node)) {
321319
throw Exceptions.InternalError("Wrong NodeCollection.AddName arguments: nameIndex[node.Name]!=null!", CoreLog.Instance);
322-
nameIndex.Add(name, node);
320+
}
323321
}
324322

325323
/// <exception cref="InvalidOperationException">Internal error.</exception>
326324
internal void CheckIntegrity()
327325
{
328326
foreach (var node in list) {
329-
var name = node.Name;
330-
if (!nameIndex.ContainsKey(name))
331-
throw Exceptions.InternalError("Integrity check failed.", CoreLog.Instance);
332-
if (node!=nameIndex[name])
327+
if (!nameIndex.TryGetValue(node.Name, out var value) || value != node) {
333328
throw Exceptions.InternalError("Integrity check failed.", CoreLog.Instance);
329+
}
334330
}
335331
}
336332

Orm/Xtensive.Orm/Orm/Building/Builders/AttributeProcessor.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -387,12 +387,10 @@ private void ProcessKeyFields(string[] source, IDictionary<string, Direction> ta
387387

388388
context.Validator.ValidateName(result.First, ValidationRule.Column);
389389

390-
if (target.ContainsKey(result.First)) {
390+
if (!target.TryAdd(result.First, result.Second)) {
391391
throw new DomainBuilderException(
392392
string.Format(Strings.ExIndexAlreadyContainsField, fieldName));
393393
}
394-
395-
target.Add(result.First, result.Second);
396394
}
397395
}
398396

Orm/Xtensive.Orm/Orm/Building/Builders/ModelBuilder.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -464,16 +464,16 @@ private void RegiserReferences(Dictionary<TypeInfo, int> referenceRegistrator, p
464464
if (typeImplementors.Any())
465465
{
466466
foreach (var implementor in typeImplementors)
467-
if (referenceRegistrator.ContainsKey(implementor))
468-
referenceRegistrator[implementor] += 1;
467+
if (referenceRegistrator.TryGetValue(implementor, out var refCount))
468+
referenceRegistrator[implementor] = refCount + 1;
469469
}
470470
else {
471-
if (referenceRegistrator.ContainsKey(type))
472-
referenceRegistrator[type] += 1;
471+
if (referenceRegistrator.TryGetValue(type, out var refCount))
472+
referenceRegistrator[type] = refCount + 1;
473473
if (descendantTypes.Any()) {
474474
foreach (var descendant in descendantTypes) {
475-
if (referenceRegistrator.ContainsKey(descendant))
476-
referenceRegistrator[descendant] += 1;
475+
if (referenceRegistrator.TryGetValue(descendant, out var refCount1))
476+
referenceRegistrator[descendant] = refCount1 + 1;
477477
}
478478
}
479479
}

Orm/Xtensive.Orm/Orm/Internals/EntitySetState.cs

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -161,10 +161,7 @@ public bool Contains(Key key)
161161
/// <param name="key">The key to add.</param>
162162
public void Add(Key key)
163163
{
164-
if (removedKeys.ContainsKey(key)) {
165-
_ = removedKeys.Remove(key);
166-
}
167-
else {
164+
if (!removedKeys.Remove(key)) {
168165
addedKeys[key] = key;
169166
}
170167
if (TotalItemCount != null) {
@@ -183,13 +180,10 @@ public void Add(Key key)
183180
/// <param name="key">The key to remove.</param>
184181
public void Remove(Key key)
185182
{
186-
if (addedKeys.ContainsKey(key)) {
187-
_ = addedKeys.Remove(key);
188-
}
189-
else {
183+
if (!addedKeys.Remove(key)) {
190184
removedKeys[key] = key;
191185
}
192-
if (TotalItemCount!=null) {
186+
if (TotalItemCount != null) {
193187
TotalItemCount--;
194188
}
195189

@@ -394,10 +388,7 @@ public void UpdateCachedState(IEnumerable<Key> syncronizedKeys, long? count)
394388
FetchedKeys.Clear();
395389
var becameRemovedOnSever = new HashSet<Key>(removedKeys.Keys);
396390
foreach (var key in syncronizedKeys) {
397-
if (addedKeys.ContainsKey(key)) {
398-
_ = addedKeys.Remove(key);
399-
}
400-
else if (becameRemovedOnSever.Contains(key)) {
391+
if (!addedKeys.Remove(key)) {
401392
_ = becameRemovedOnSever.Remove(key);
402393
}
403394
FetchedKeys.Add(key);

Orm/Xtensive.Orm/Orm/Internals/Prefetch/EntityGroupTask.cs

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -86,18 +86,8 @@ public CacheKey(int[] columnIndexes, TypeInfo type, int cachedHashCode)
8686

8787
public CompilableProvider Provider { get; private set; }
8888

89-
public void AddKey(Key key, bool exactType)
90-
{
91-
if (keys == null) {
92-
keys = new Dictionary<Key, bool>();
93-
}
94-
95-
if (keys.ContainsKey(key)) {
96-
return;
97-
}
98-
99-
keys.Add(key, exactType);
100-
}
89+
public void AddKey(Key key, bool exactType) =>
90+
(keys ??= new Dictionary<Key, bool>()).TryAdd(key, exactType);
10191

10292
public void RegisterQueryTasks()
10393
{

Orm/Xtensive.Orm/Orm/Linq/MemberCompilation/MemberCompilerProvider.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (C) 2009-2020 Xtensive LLC.
1+
// Copyright (C) 2009-2024 Xtensive LLC.
22
// This code is distributed under MIT license terms.
33
// See the License.txt file in the project root for more information.
44
// Created by: Denis Krjuchkov
@@ -103,14 +103,15 @@ private void UpdateRegistry(
103103
{
104104
foreach (var (targetMember, compiler) in newRegistrations) {
105105
var key = GetCompilerKey(targetMember);
106-
if (conflictHandlingMethod != ConflictHandlingMethod.Overwrite && compilers.ContainsKey(key)) {
107-
if (conflictHandlingMethod == ConflictHandlingMethod.ReportError) {
108-
throw new InvalidOperationException(string.Format(
109-
Strings.ExCompilerForXIsAlreadyRegistered, targetMember.GetFullName(true)));
106+
if (!compilers.TryAdd(key, compiler)) {
107+
switch (conflictHandlingMethod) {
108+
case ConflictHandlingMethod.Overwrite:
109+
compilers[key] = compiler;
110+
break;
111+
case ConflictHandlingMethod.ReportError:
112+
throw new InvalidOperationException(string.Format(Strings.ExCompilerForXIsAlreadyRegistered, targetMember.GetFullName(true)));
110113
}
111-
continue;
112114
}
113-
compilers[key] = compiler;
114115
}
115116
}
116117

0 commit comments

Comments
 (0)