Skip to content

Commit 349d1da

Browse files
committed
Add TryGetObject/TryGetList and TryGetValue extensions for easier pattern matching
1 parent a2e5d97 commit 349d1da

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

ServiceStack/src/ServiceStack.AI.Chat/GoogleProvider.cs

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,18 @@ public string GeminiChatSummaryJson(Dictionary<string, object> geminiChat)
1212
{
1313
var origJson = JSON.stringify(geminiChat);
1414
var clone = (Dictionary<string,object>) JSON.parse(origJson);
15-
if (clone.TryGetValue("contents", out var oContents)
16-
&& oContents is List<object> contents)
15+
if (clone.TryGetList("contents", out var contents))
1716
{
1817
foreach (var oContent in contents)
1918
{
2019
if (oContent is Dictionary<string, object> content
21-
&& content.TryGetValue("parts", out var oParts)
22-
&& oParts is List<object> parts)
20+
&& content.TryGetList("parts", out var parts))
2321
{
2422
foreach (var oPart in parts)
2523
{
2624
if (oPart is Dictionary<string, object> part
27-
&& part.TryGetValue("inline_data", out var oInlineData)
28-
&& oInlineData is Dictionary<string, object> inlineData
29-
&& inlineData.TryGetValue("data", out var oData)
30-
&& oData is string data)
25+
&& part.TryGetObject("inline_data", out var inlineData)
26+
&& inlineData.TryGetValue<string>("data", out var data))
3127
{
3228
inlineData["data"] = $"({data.Length})";
3329
}

ServiceStack/src/ServiceStack.Common/DictionaryExtensions.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,27 @@ public static TValue GetValue<TValue, TKey>(this Dictionary<TKey, TValue> dictio
1717
return dictionary.TryGetValue(key, out var value) ? value : defaultValue();
1818
}
1919

20+
public static bool TryGetValue<T>(this Dictionary<string, object> dictionary, string key, out T value)
21+
{
22+
if (dictionary.TryGetValue(key, out var objValue) && objValue is T theValue)
23+
{
24+
value = theValue;
25+
return true;
26+
}
27+
value = default;
28+
return false;
29+
}
30+
31+
public static bool TryGetObject(this Dictionary<string, object> dictionary, string key, out Dictionary<string, object> value)
32+
{
33+
return TryGetValue(dictionary, key, out value);
34+
}
35+
36+
public static bool TryGetList(this Dictionary<string, object> dictionary, string key, out List<object> value)
37+
{
38+
return TryGetValue(dictionary, key, out value);
39+
}
40+
2041
public static bool IsNullOrEmpty(this IDictionary dictionary)
2142
{
2243
return dictionary == null || dictionary.Count == 0;

0 commit comments

Comments
 (0)