Select specific date from datatable - c#

I want to select and re-assign the datatable after spesific hour. I use below code;
dtMasterPivot = dtMasterPivot.AsEnumerable().Where(x => x.Field<DateTime>("SAMPLE_TIME").Hour >= 4).CopyToDataTable();
Like above what i want is only select the data after 04:00. However, it doesn't work. It still brings the before 04:00.

This works as advertised:
class Program
{
static void Main(string[] args)
{
var dT = new DataTable();
dT.Columns.Add("Id", typeof(int));
dT.Columns.Add("Sample_Time", typeof(DateTime));
dT.Columns.Add("Misc", typeof(string));
var row = dT.NewRow();
row[0] = 1;
row[1] = new DateTime(2017, 8, 3, 15, 15, 0);
row[2] = "3:15 PM";
dT.Rows.Add(row);
row = dT.NewRow();
row[0] = 2;
row[1] = new DateTime(2017, 8, 3, 3, 59, 0);
row[2] = "3:59 AM";
dT.Rows.Add(row);
row = dT.NewRow();
row[0] = 3;
row[1] = new DateTime(2017, 8, 3, 12, 0, 0);
row[2] = "Noon";
dT.Rows.Add(row);
dT = dT.AsEnumerable().Where(x => x.Field<DateTime>("Sample_Time").Hour >= 4).CopyToDataTable();
for (int i = 0; i < dT.Rows.Count; i++)
{
Console.WriteLine((string)dT.Rows[i][2]);
}
Console.ReadKey();
}
}
Silly question really, but are you sure about your field names? And also whether you are using 12/24 hour clock?

Related

Sum column where (condition) with datatable

Suppose I have the following datatable, and i want to sum all rows where column is "money" where the month is may.
+--------------------+-------+
| Date | money |
+--------------------+-------+
| 5/3/2020 8:00:00 | 20 |
+--------------------+-------+
| 5/3/2020 11:00:00 | 10 |
+--------------------+-------+
| 8/3/2020 12:00:00 | 5 |
+--------------------+-------+
| 9/7/2020 10:00:00 | 56 |
+--------------------+-------+
| 2/11/2020 13:00:00 | 45 |
+--------------------+-------+
Expected result is 30, my code gives 0 as answer
My code is:
string data= dt.AsEnumerable()
.Where(y => y.Field<DateTime>("Date").Month==m)
.Sum(x => x.Field<int>("money"))
.ToString();
Note, I don't want a sulotion with iteration, but similar to mine (Like sql style "select from where...")
My result is 30.
var dt = new DataTable();
dt.Columns.Add("Date", typeof(DateTime));
dt.Columns.Add("money", typeof(int));
var row = dt.NewRow();
row["Date"] = new DateTime(2020, 5, 3);
row["money"] = 20;
dt.Rows.Add(row);
row = dt.NewRow();
row["Date"] = new DateTime(2020, 5, 3);
row["money"] = 10;
dt.Rows.Add(row);
row = dt.NewRow();
row["Date"] = new DateTime(2020, 8, 3);
row["money"] = 5;
dt.Rows.Add(row);
row = dt.NewRow();
row["Date"] = new DateTime(2020, 9, 7);
row["money"] = 56;
dt.Rows.Add(row);
row = dt.NewRow();
row["Date"] = new DateTime(2020, 2, 11);
row["money"] = 45;
dt.Rows.Add(row);
var sumOfValuesInMarch = dt.AsEnumerable()
.Where(x => x.Field<DateTime>("Date").Month == 5)
.Sum(x => x.Field<int>("money"))
.ToString(); // 30

Fill DataGridView in new columns

I have a DataGridView that is being filled with DataTable → Fill() method.
I want to add another Table in the same DataGridView, in the next column, just when the other one ends. Is it possible?
Now I have something like this
da.Fill(dt);
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
dataGridView1.DataSource = dt;
I want to add another DataTable to the same DataGridView in new columns. Thanks
Use the Merge function of DataTable and then shift elements up. See codes below:
private void AddTwoDataTable()
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID1", typeof(int));
dt1.Columns.Add("Value1", typeof(string));
dt1.Columns.Add("Value2", typeof(string));
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID2", typeof(int));
dt2.Columns.Add("Value3", typeof(string));
dt1.Rows.Add(new object[] { 1, "a", "ab"});
dt1.Rows.Add(new object[] { 2, "b", "bc" });
dt1.Rows.Add(new object[] { 3, "c", "cd" });
dt1.Rows.Add(new object[] { 4, "d", "de" });
dt2.Rows.Add(new object[] { 101, "x" });
dt2.Rows.Add(new object[] { 102, "y" });
dt2.Rows.Add(new object[] { 103, "y" });
var newtable = MergetwoTables( dt1, dt2 );
dataGridView1.DataSource = newtable;
}
public static DataTable MergetwoTables(DataTable dt1, DataTable dt2)
{
DataTable table = new DataTable("NewTable");
table.Merge(dt1);
table.Merge(dt2);
int maxRows1 = dt1.Rows.Count;
int maxColu1 = dt1.Columns.Count;
int maxRows2 = dt2.Rows.Count;
int maxColu2 = dt2.Columns.Count;
// copy elements from new rows
for (int r = maxRows1; r < maxRows1 + maxRows2; r++)
for (int c = maxColu1; c < maxColu1 + maxColu2; c++)
table.Rows[r - maxRows1][c] = table.Rows[r][c];
//delete new rows
var maxrows = maxRows1 > maxRows2 ? maxRows1 : maxRows2;
for (int r = maxRows1 + maxRows2 - 1; r >= maxrows; r--)
table.Rows[r].Delete();
return table;
}
Output:

multiple series in column chart asp.net 4.0

I am trying to create a StackedColumn chart in my asp.net application. So I have a datatable like this -
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("Phase", typeof(string));
dtTemp.Columns.Add("Status", typeof(string));
dtTemp.Columns.Add("Count", typeof(int));
dtTemp.Rows.Add("Initiate", "Pending", 10
dtTemp.Rows.Add("Initiate", "OnHold", 20);
dtTemp.Rows.Add("Initiate", "Rejected", 3);
dtTemp.Rows.Add("Initiate", "Cancelled", 5);
dtTemp.Rows.Add("Initiate", "Pending IT", 2);
dtTemp.Rows.Add("Setup", "Setup", 25);
Now I want the chart to display 2 column, first column will show the Initiate phase data with different status data. And 2nd column will show setup phase data. I have tried like this -
foreach (DataRow row in dtTemp.Rows)
{
string seriesName = row["Status"].ToString();
chart_ProjectStatus.Series.Add(seriesName);
chart_ProjectStatus.Series[seriesName].ChartType = SeriesChartType.StackedColumn;
chart_ProjectStatus.Series[seriesName].ChartArea = "ChartArea1";
chart_ProjectStatus.Series[seriesName].CustomProperties = "DrawingStyle=Cylinder, MaxPixelPointWidth=50";
chart_ProjectStatus.Series[seriesName].Points.AddXY(row["Phase"].ToString(), Convert.ToInt32(row["Count"].ToString()));
}
But I am getting only one column -
Please some one help me.
Thanks in advance
Gulrej
<b> Hope this will Help you </b>
DataTable dtTemp = new DataTable();
dtTemp.Columns.Add("Phase", typeof(string));
dtTemp.Columns.Add("Status", typeof(string));
dtTemp.Columns.Add("Count", typeof(int));
dtTemp.Columns.Add("StackGroupName", typeof(string));
dtTemp.Rows.Add("Initiate", "Pending", 10, "Group1");
dtTemp.Rows.Add("Initiate", "OnHold", 20, "Group1");
dtTemp.Rows.Add("Initiate", "Rejected", 3, "Group1");
dtTemp.Rows.Add("Initiate", "Cancelled", 5, "Group1");
dtTemp.Rows.Add("Initiate", "PendingIT", 2, "Group1");
dtTemp.Rows.Add("Setup", "Setup", 25, "Group2");
dtTemp.Rows.Add("Setup", "INSTALLED", 55, "Group2");
dtTemp.AcceptChanges();
Series ss;
for (int i = 0; i < dtTemp.Rows.Count; i++)
{
ss = new Series();
ss.Name = dtTemp.Rows[i][1].ToString();
ss.ChartType = SeriesChartType.StackedColumn;
ss["StackedGroupName"] = dtTemp.Rows[i]["StackGroupName"].ToString();
ss["DrawingStyle"] = "Cylinder";
ss.Points.AddXY(Convert.ToString(dtTemp.Rows[i]["Phase"]), Convert.ToInt32(dtTemp.Rows[i]["Count"]));
ss.IsValueShownAsLabel = true;
ChartSideBySideStacked.Series.Add(ss);
}
ChartArea chartAread = new ChartArea();
chartAread.Area3DStyle.Enable3D = true;
chartAread.Area3DStyle.Rotation = 5;
chartAread.Area3DStyle.Inclination = 10;
chartAread.Area3DStyle.IsRightAngleAxes = false;
ChartSideBySideStacked.ChartAreas.Add(chartAread);
ChartSideBySideStacked.Legends.Add(new Legend("CHartLEgend"));
ChartSideBySideStacked.AlignDataPointsByAxisLabel(); // Chart Object Name : ChartSideBySideStacked
Enable 3D
U must Provide Stacked Group Name for Each Series
Set Rotation Angle
Set Inclination and IsRightAngleAxes
this one is working fine ... please note i am using VS 2010.. Asp.Net

Asp.Net chart with multiple series and multiple values on the y axis

I have a datatable that looks like this:
Data Value 1 Value 2 Value 3
series1 32 -2 46
series2 -62 99
series3 19 23 98
On the chart I will need it to look like this:
32 -2 46 -62 99 19 23 98
series1 series2 series3
and the legend : value 1, value 2, value 3
the codes I have tried:
private void LoadChartCurrencyTotal(DataTable initialDataSource)
{
DataTable pivotedDt = Pivot(initialDataSource);
chart1.DataSource = pivotedDt;
foreach (DataRow dr in pivotedDt.Rows)
{
Series series = new Series(dr["Data"].ToString());
List<string> colNames = (from DataColumn col in pivotedDt.Columns where col.ColumnName != "Data" select col.ColumnName).ToList();
series.XValueMember = "Data";
series.YValueMembers = string.Join(",", colNames);
chart1.Series.Add(series);
}
chart1.DataBind();
FormatChart(chart1);
}
this returns Data points insertion error. Only 1 Y values can be set for this data series. because of the joined column names.
Also tried:
private void LoadChartCurrencyTotal(DataTable initialDataSource)
{
DataTable pivotedDt = Pivot(initialDataSource);
foreach (DataRow pivotDr in pivotedDt.Rows)
{
Series serie = new Series(pivotDr["Data"].ToString());
List<decimal?> colValues = new List<decimal?>();
foreach (DataColumn col in pivotedDt.Columns)
{
if (col.ColumnName != "Data")
{
//colValues.Add(pivotDr[col.ColumnName] != DBNull.Value
// ? decimal.Parse(pivotDr[col.ColumnName].ToString())
// : new decimal?());
decimal? colValue = pivotDr[col.ColumnName] != DBNull.Value
? decimal.Parse(pivotDr[col.ColumnName].ToString())
: new decimal?();
serie.Points.AddXY(pivotDr["Data"], colValue);
}
}
//serie.Points.AddXY(pivotDr["Data"], string.Join(",", colValues));
chart1.Series.Add(serie);
}
FormatChart(chart1);
}
This compiles but the result is completly messed up: The legend sais series1, series2, series3 and the result is:
32 -62 19 -2 23 46 99 98
series1 series2 series3
I get the results per column not per row.
And the last I have tried is:
DataView pivotedDv = pivotedDt.AsDataView();
chart1.DataBindTable(pivotedDv, pivotedDt.Columns[0].ColumnName);
but this only returns:
0.00 0.00 0.00
series1 series2 series3
and the legend: 0.00
Hope someone has a clue how this should be acomplished. but please, no drag and drop and click solutions, but code.
Thanks
I think I have got this working how you like using the following code. Hope this helps:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = GetTestData();
LoadChartCurrencyTotal(dt);
}
}
private void LoadChartCurrencyTotal(DataTable initialDataSource)
{
for (int i = 1; i < initialDataSource.Columns.Count; i++)
{
Series series = new Series();
foreach (DataRow dr in initialDataSource.Rows)
{
int y = (int)dr[i];
series.Points.AddXY(dr["Data"].ToString(), y);
}
Chart1.Series.Add(series);
}
}
private DataTable GetTestData()
{
DataTable dt = new DataTable();
dt.Columns.Add("Data", Type.GetType("System.String"));
dt.Columns.Add("Value1", Type.GetType("System.Int32"));
dt.Columns.Add("Value2", Type.GetType("System.Int32"));
dt.Columns.Add("Value3", Type.GetType("System.Int32"));
DataRow dr1 = dt.NewRow();
dr1["Data"] = "series1";
dr1["Value1"] = 32;
dr1["Value2"] = -2;
dr1["Value3"] = 46;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["Data"] = "series2";
dr2["Value1"] = -62;
dr2["Value2"] = 0;
dr2["Value3"] = 99;
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["Data"] = "series3";
dr3["Value1"] = 19;
dr3["Value2"] = 23;
dr3["Value3"] = 98;
dt.Rows.Add(dr3);
return dt;
}

Filling in missing dates in datatable using a linq group by date query

I am trying to fill missing date in data table for report.
for example:
data table collection :
2010-01-01 : 5
2010-01-02 : 4
2010-01-03 : 2
2010-01-05 : 6
but I want result like this:
2010-01-01 : 5
2010-01-02 : 4
2010-01-03 : 2
2010-01-04 : 0
2010-01-05 : 6
var total = from row in dt2.AsEnumerable()
where row.Field<UInt32>("Super Category") == j
group row by row.Field<string>("Activation Date") into sales
orderby sales.Key
select new
{
Name = sales.Key,
CountOfClients = sales.Count()
};
How can I do that?
This works:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("dt", typeof(DateTime)));
dt.Columns.Add(new DataColumn("num", typeof(int)));
dt.Rows.Add(new DateTime(2010, 1, 1), 5);
dt.Rows.Add(new DateTime(2010, 1, 2), 4);
dt.Rows.Add(new DateTime(2010, 1, 3), 2);
dt.Rows.Add(new DateTime(2010, 1, 5), 6);
dt.Rows.Add(new DateTime(2010, 1, 8), 6);
dt.Rows.Add(new DateTime(2010, 1, 9), 6);
dt.Rows.Add(new DateTime(2010, 1, 12), 6);
DateTime minDT = dt.Rows.Cast<DataRow>().Min(row => (DateTime)row["dt"]);
DateTime maxDT = dt.Rows.Cast<DataRow>().Max(row => (DateTime)row["dt"]);
// Create all the dates that should be in table
List<DateTime> dts = new List<DateTime>();
DateTime DT = minDT;
while (DT <= maxDT)
{
dts.Add(DT);
DT = DT.AddDays(1);
}
// Find the dates that should be in table but aren't
var DTsNotInTable = dts.Except(dt.Rows.Cast<DataRow>().Select(row => (DateTime)row["dt"]));
foreach (DateTime dateTime in DTsNotInTable)
dt.Rows.Add(dateTime, 0);
// Order the results collection
var ordered = dt.Rows.Cast<DataRow>().OrderBy(row => (DateTime)row["dt"]);
// Create a DataTable object
DataTable dt2 = ordered.CopyToDataTable();
dt2 table will contain results without DateTime gaps ordered by DateTime column.
try something like this.
DateTime startDate = collection.first().date;
DateTime endDate = collection.last().date;
While(startDate < endDate)
{
// compare if collection date is valid
startDate.AddDays(1);
}

Categories

Resources