Add commas to Dictionary integer values

Brian 161 Reputation points
2021-10-16T17:15:42.453+00:00

I have a SQL stored procedure that returns two fields - Key (varchars) and Value (integers). In my page model, I execute the stored procedure and store the results in a dictionary.

public IDictionary<string, int> Result = new Dictionary<string, int>();

Result = _db.KeyValue.FromSqlRaw($"exec myStoredProcedure").ToDictionary(t => t.Key, t => t.Value);

On my razor page I can get the values simply by:

@Model.Result["Field1"].ToString("N0")

This works great, however I'd like to use the DRY principle, and have the dictionary preloaded with the commas instead of using ".ToString("N0")" for every result that I return.

Based on what I was googling, I don't think I can use the data annotation [DisplayFormat(DataFormatString = "{0:N0}")] on the Dictionary.

If that's the case, could another option be to modify the LINQ statement to format the ints with commas just after retrieving the values from the stored procedure?

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,761 Reputation points
    2021-10-16T17:26:35.627+00:00

    Do you mean you want to format your ints in your controller? You can just format it inside your ToDictionary call.

    public IDictionary<string, string> Result = new Dictionary<string, string>();
    
    Result = _db.KeyValue.FromSqlRaw($"exec myStoredProcedure").ToDictionary(t => t.Key, t => t.Value.ToString("N0"));
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.