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();
Assuming you want the answer as List<anonymous>
then I would convert the DataTable
to a Dictionary
and then use monthsRange
to create the final List
:
var monthsRange = Enumerable.Range(1, 12)
.Select(e => new DateTime(2000,e,20).ToString("MMM", CultureInfo.GetCultureInfo("en-US")))
.ToList();
var dtd = dt.AsEnumerable().ToDictionary(r => r.Field<string>("Data"), r => r.Field<string>("Quantidade"));
var ans = monthsRange.Select(Mes => new {
Mes,
Qt = dtd.TryGetValue(Mes, out var qt)
? qt
: "0"
})
.ToList();