Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8365071
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T12:34:29+00:00 2026-06-09T12:34:29+00:00

I’m looking for an extension method or any other suggestion that can help me

  • 0

I’m looking for an extension method or any other suggestion that can help me make this code as concise as possible.

foreach( Layer lyr in this.ProgramLayers )
  foreach( UWBCEvent evt in this.BcEvents.IncludedEvents )
    EventGroupLayerLosses[new EventGroupIDLayerTuple(evt.EventGroupID, lyr)] += 
       GetEL(evt.AsIfs, lyr.LimitInMillions, lyr.AttachmentInMillions);

The above code has a fairly clear purpose, I’m bucketing values into groups with a compound key. However, this code will fail because the dictionary is initially empty and the += operator won’t know to start the bucket off at 0.

The best I can come up with is this:

public V AddOrSet<K, V>(this Dictionary<K, V> dict, K key, V value)
{
    if( dict.ContainsKey(key) )
        dict[key] += value;
    else
        dict[key] = value;
}

But of course, even that won’t compile because there’s no way to restrict the type of V such that the operator += exists.

Rules

  • Only one iteration through the double for loop. Not allowed to loop through once before to initialize the dictionary with 0 values.
  • Helper method or extension method can be used, but I want the inner loop to be a one liner.
  • Be as generic and reusable as possible so that I don’t need to create a bunch of identical functions for similar bucketing with different types (decimals, ints, etc).

For reference – elsewhere in the class the key is defined as an actual Tuple (just with named parameters), which is why it can be used as a dictionary key:

private Dictionary<EventGroupIDLayerTuple, Decimal> _EventGroupLayerLosses;
public class EventGroupIDLayerTuple : Tuple<Int32, Layer>
{
    public EventGroupIDLayerTuple(Int32 EventGroupID, Layer Layer) : base(EventGroupID, Layer) { }
    public Int32 EventGroupID { get { return this.Item1; } }
    public Layer Layer { get { return this.Item2; } }
}

Solution

Thanks to Jon Skeet for the idea of passing a Lambda function as a third parameter to my extension method. No need to even restrict it to a += operation anymore. It’s generic enough any operation can be passed to set the new value if a value already exists.

//Sets dictionary value using the provided value. If a value already exists, 
//uses the lambda function provided to compute the new value.
public static void UpdateOrSet<K, V>(this Dictionary<K, V> dict, K key, V value, Func<V, V, V> operation)
{
    V currentValue;
    if( dict.TryGetValue(key, out currentValue) )
        dict[key] = operation(currentValue, value);
    else
        dict[key] = value;
}

Examples:

mySums.UpdateOrSet("Bucket1", 12, (x, y) => x + y);
myStrs.UpdateOrSet("Animals", "Dog", (x, y) => x + ", " + y);
myLists.UpdateOrSet("Animals", (List<T>) Dogs, (x, y) => x.AddRange(y));

Endless fun!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T12:34:30+00:00Added an answer on June 9, 2026 at 12:34 pm

    Firstly, I’d advise against doing everything you can to make something as short as possible at the potential cost of readability. For example, I’d add braces around the foreach bodies, and if a more readable solution ended up being two lines rather than one, I’d be happy with that.

    Secondly, I’m going to assume that for any of the types you’re interested in, the default value is a natural zero.

    Now, you can write:

    public static void AddOrSet<K, V>(this Dictionary<K, V> dict,
                                      K key, V value, Func<V, V, V> addition)
    {
        V existing;
        dict.TryGetValue(key, out existing);
        dict[key] = addition(existing, value);
    }
    

    Then you can use:

    EventGroupLayerLosses.AddOrSet(new EventGroupIDLayerTuple(evt.EventGroupID, lyr),
        GetEL(evt.AsIfs, lyr.LimitInMillions, lyr.AttachmentInMillions),
        (x, y) => x + y);
    

    Using ConcurrentDictionary would work well too.

    Additionally, I would try to rework this as a LINQ query if you can. I wouldn’t be surprised if a mixture of GroupBy, Sum and ToDictionary allowed you to express the whole thing declaratively.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
Does anyone know how can I replace this 2 symbol below from the string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.