In C #, you can add a value to a collection and at the same time assign it to another variable

I use a conditional statement to check if the value in the collection is already cached, and if not, call the appropriate method as follows:

facilityQuantity = facilityFundedAmts.ContainsKey(facilityId) ? facilityFundedAmts[facilityId] : facilityHolding.Funded();

Is it possible to somehow add the collection facilityHolding.Funded()to mine facilityFundedAmtson the same line?

+4
source share
3 answers

What about an extension method to encapsulate what you are doing? You can pass it a key and a function that you can use to create a value if it does not exist:

public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> source, TKey key, Func<TValue> valueFunc)
{
    TValue value;

    if (!source.TryGetValue(key, out value))
    {
        value = valueFunc();
        source.Add(key, value);
    }

    return value;
}

And use it as below:

facilityQuantity = facilityFundedAmts.GetOrAdd(facilityId, () => facilityHolding.Funded());

, , , Func<TValue>, :

facilityQuantity = facilityFundedAmts.GetOrAdd(facilityId, facilityHolding.Funded);
+13

, / if ... else:

facilityFundedAmts.ContainsKey(facilityId) ? facilityQuantity = facilityFundedAmts[facilityId] : facilityFundedAmts.Add(facilityQuantity = facilityHolding.Funded());

TryGetValue , , , :

if (!facilityFundedAmts.TryGetValue(facilityId, out facilityQuantity)) {
  facilityFundedAmts.Add(facilityQuantity = facilityHolding.Funded());
}
+2

- Holding.Funded() facilityFundedAmts ?

:

facilityQuantity = facilityFundedAmts.ContainsKey(facilityId) ? facilityFundedAmts[facilityId] : facilityFundedAmts[facilityId] = facilityHolding.Funded();

, facilityFundedAmts[], , - getter.

, ( , Dictionary, , ...), , , :

if(facilityFundedAmts.ContainsKey(facilityId))
  facilityQuantity = facilityFundedAmts[facilityId]
else
  facilityFundedAmts[facilityId] = facilityQuantity = facilityHolding.Funded();

. ( ), , , .

, .

if(!facilityFundedAmts.TryGetValue(facilityId, out facilityQuantity)) facilityFundedAmts.Add(facilityId, facilityQuantity = facilityHolding.Funded());

. , , , .

+2
source

Source: https://habr.com/ru/post/1583787/


All Articles