'How to compare all elements between Datatable and Array's months?
I'd like to ask you guys for a question that helps from you.
I have a DataTable with months and amounts, as shown below, and an array named after all the months of the year. How could I build a structure that would return the months of the year with the quantities described in the DataTable along with the other months with the quantity in zeros?
Before
Mes Qt
Dec 6
Jan 2
Nov 2
After
Mes Qt
Jan 2
Fev 0
Mar 0
Abr 0
Mai 0
Jun 0
Jul 0
Ago 0
Set 0
Out 0
Nov 2
Dec 6
My code:
DataTable dt = new DataTable();
dt.Columns.Add("Data");
dt.Columns.Add("Quantidade");
dt.Rows.Add(new object[] { "Dec", 6 });
dt.Rows.Add(new object[] { "Jan", 1 });
dt.Rows.Add(new object[] { "Nov", 4 });
var monthsRange = Enumerable.Range(1, 12)
.Select(e => e > 0 ? Convert.ToDateTime("20/" + e + "/2000").ToString("MMM", CultureInfo.GetCultureInfo("en-US")) : "")
.ToArray();
Solution 1:[1]
I would use something like that (I wasn't sure what type of data is intended for output):
DataTable initialData = new DataTable();
initialData.Columns.Add("Mes");
initialData.Columns.Add("Qt");
initialData.Rows.Add(new object[] { "Dec", 6 });
initialData.Rows.Add(new object[] { "Jan", 1 });
initialData.Rows.Add(new object[] { "Nov", 4 });
DataTable outputData = new DataTable();
outputData.Columns.Add("Mes");
outputData.Columns.Add("Qt");
foreach (var month in Enumerable.Range(1, 12))
{
var monthName = new DateTime(2000, month, 1).ToString("MMM", CultureInfo.GetCultureInfo("en-US"));
int.TryParse(initialData.Select($"Mes='{monthName}'").FirstOrDefault()?["Qt"].ToString(), out int count);
outputData.Rows.Add(new object[] { monthName, count });
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
