question

Brian-7574 avatar image
0 Votes"
Brian-7574 asked Paul-5034 answered

Add commas to Dictionary integer values

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?


dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Paul-5034 avatar image
0 Votes"
Paul-5034 answered

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"));
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.