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();
CodePudding user response:
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")))
.ToArray();
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();
CodePudding user response:
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 });
}