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

  • Home
  • SEARCH
  • 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 359145
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T12:21:58+00:00 2026-05-12T12:21:58+00:00

In my code I’m creating a number of lookup tables. var Dict1 = data1.ToDictionary(dim

  • 0

In my code I’m creating a number of lookup tables.

var Dict1 = data1.ToDictionary(dim => new { dim.Val1,dim.Val2,.. }  );
var Dict2 = data2.ToDictionary(dim => new { dim.Val1,dim.Val2,.. }  );

sometime there are duplicate key values, so I tried to use a catch block

try
{
   var Dict1 = data1.ToDictionary(dim => new { dim.Val1,dim.Val2,.. }  );
}
catch (ArgumentException ex)
{
    Console.WriteLine("Duplicate values in Data1 {0}",ex);
    throw;
}

but this approach means that the Dicts won’t be visible to the rest of the code.

Any ideas on how to do this?

Edit: the intent of the catch block is to report which dictionary creation failed.

  • 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-05-12T12:21:59+00:00Added an answer on May 12, 2026 at 12:21 pm

    Declare and add a single element above the try, and then add the rest inside. Since you’re specifically worried about duplicate keys, adding the first key/item gets you the type without the risk.

    EDIT: I think just inferring the type, without adding the first element, is slightly better. While the usage is a bit cumbersome, it’ll make it easier to add remaining elements (as opposed to clearing the dictionary, and then adding – or having to add everything after the 1st one – really only cleanly doable if you’re consuming an IEnumerable).

    var dict1 = InferDictionary(new { Value1 = 0, Value2 = "string" }, new DataItem());
    try {
      data1.AddToDictionary(
         dict1, 
         dim => new { Value1 = dim.Val1, Value2 = dim.Val2 }
      );
    } catch ... {
        ...
    }
    
    static IDictionary<TKey, TValue> InferDictionary<TKey, TValue>(TKey keyPrototype, TValue valuePrototype) {
        return new Dictionary<TKey, TValue>();
    }
    

    Or, create a convenience function to catch the exception for you:

    var dict1 = TryCatch(
      () => 
          data1.ToDictionary(dim => new { 
             Value1 = dim.Val1,
             Value2 = dum.Val2
          }
      , (ArgumentException ex) => {
          Console.WriteLine("Duplicate values in Data1 {0}", ex);
         // throw(ex) works as well, and shouldn't screw the callstack up much
         // But I happen to like making it explicit
         return false; 
      }
    );
    
    static TResult TryCatch<TResult, TException>(Func<TResult> @try, Func<TException, bool> @catch) where TException : Exception {
       try {
           return @try();
       } catch (Exception ex) {
           TException tEx = ex as TException;
           if (tEx != null && @catch(ex)) {
              // handled
           } else {
              throw;
           } 
       }
    }
    

    The caveat of this is that you can’t call TryCatch<,> in the “natural” ways:

    // Not enough info to infer TException
    var d = TryCatch(() => DoStuff(), ex => true);
    
    // Can't infer only TResult
    var d = TryCatch<ArgumentException>(() => DoStuff(), ex => true);
    

    which, since you can’t specify TResult, forces you into the somewhat odd syntax of declaring TException on the lambda:

    var d = TryCatch(() => DoStuff(), (ArgumentException ex) => true);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Code to create new form instance of a closed form using form name I
Code I have: cell_val = CStr(Nz(fld.value, )) Dim iter As Long For iter =
Code: ArrayList <Integer> marks = new ArrayList(); private void addButtonActionPerformed(java.awt.event.ActionEvent evt) { Collections.addAll(marks, (Integer.parseInt(markInput.getText())));
Code 1: ArrayList arr = new ArrayList(); arr.add(3); arr.add(ss); Code 2: ArrayList<Object> arr =
Code example: var Events = $({}); Events.on('myCustomEvent', function(){ console.log('myCustomEvent 1') }) Events.trigger('myCustomEvent'); // I
Code: function remove_comment(){ var id = bla; Msg().prompt( blabla , function(){ Ajax().post( id= +
Code bellow will create eventstore for named connection. var es = Wireup.Init() .UsingSqlPersistence(DB) .Build();
Code below sets default values for new row if row is added using form.
Code Random Randomizer = new Random () ; cardoneA = suits[Randomizer.nextInt(suits.length)]; cardoneAv = ranks[Randomizer.nextInt(ranks.length)];
code: Random Picker = new Random(); List<String> list = new ArrayList<String>(); list.add(card1); list.add(card2); list.add(card3);

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.