I have four tables (employees, allowances,deductions and Ajenda these are main tables , when i save employees financial details i save them in a different tables as image .
I want to display the employees detail and financial details in a horizontally way .
I'm using C# and SQLServer 2012 .
first table contains employees main details , second contain employees id with there allowances and other tables .
My tables
Here is my code before somebody closes it again. I decided not to use group since there would be a lot of left outer joins which would complicate solution. Decided just to create a table and then add the data directly to the results table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable employees = new DataTable();
employees.Columns.Add("empID", typeof(int));
employees.Columns.Add("emp_name", typeof(string));
employees.Columns.Add("emp_tele", typeof(string));
employees.Rows.Add(new object[] { 1, "David", "025896325" });
employees.Rows.Add(new object[] { 2, "John", "856985658" });
employees.Rows.Add(new object[] { 3, "Micheal", "654687887" });
DataTable allowances = new DataTable();
allowances.Columns.Add("empID", typeof(int));
allowances.Columns.Add("allow_name", typeof(string));
allowances.Columns.Add("allow_Amount", typeof(int));
allowances.Rows.Add(new object[] { 1, "allow1", 100 });
allowances.Rows.Add(new object[] { 1, "allow2", 200 });
allowances.Rows.Add(new object[] { 1, "allow3", 300 });
allowances.Rows.Add(new object[] { 2, "allow1", 100 });
allowances.Rows.Add(new object[] { 2, "allow2", 200 });
DataTable deductions = new DataTable();
deductions.Columns.Add("empID", typeof(int));
deductions.Columns.Add("Dedu_name", typeof(string));
deductions.Columns.Add("Dedu_Amount", typeof(int));
deductions.Rows.Add(new object[] { 1, "ded1", 10 });
deductions.Rows.Add(new object[] { 1, "ded2", 5 });
deductions.Rows.Add(new object[] { 2, "ded1", 10 });
DataTable ajenda = new DataTable();
ajenda.Columns.Add("empID", typeof(int));
ajenda.Columns.Add("ajenda_name", typeof(string));
ajenda.Columns.Add("ajenda_Amount", typeof(int));
ajenda.Rows.Add(new object[] { 1, "aj1", 200 });
ajenda.Rows.Add(new object[] { 1, "aj1", 200 });
ajenda.Rows.Add(new object[] { 1, "aj2", 300 });
DataTable results = employees.Clone();
string[] allow_names = allowances.AsEnumerable().Select(x => x.Field<string>("allow_name")).Distinct().OrderBy(x => x).ToArray();
foreach (string name in allow_names)
{
results.Columns.Add(name, typeof(string));
}
string[] dedu_names = deductions.AsEnumerable().Select(x => x.Field<string>("Dedu_name")).Distinct().OrderBy(x => x).ToArray();
foreach (string name in dedu_names)
{
results.Columns.Add(name, typeof(string));
}
string[] ajenda_names = ajenda.AsEnumerable().Select(x => x.Field<string>("ajenda_name")).Distinct().OrderBy(x => x).ToArray();
foreach (string name in ajenda_names)
{
results.Columns.Add(name, typeof(string));
}
//add employees to result table
foreach(DataRow row in employees.AsEnumerable())
{
results.Rows.Add(row.ItemArray);
}
var groupAllownaces = allowances.AsEnumerable().GroupBy(x => x.Field<int>("empID"));
foreach (var group in groupAllownaces)
{
DataRow employeeRow = results.AsEnumerable().Where(x => x.Field<int>("empID") == group.Key).First();
foreach (DataRow row in group)
{
employeeRow[row.Field<string>("allow_name")] = row.Field<int>("allow_Amount");
}
}
var groupDeductions = deductions.AsEnumerable().GroupBy(x => x.Field<int>("empID"));
foreach (var group in groupDeductions)
{
DataRow employeeRow = results.AsEnumerable().Where(x => x.Field<int>("empID") == group.Key).First();
foreach (DataRow row in group)
{
employeeRow[row.Field<string>("Dedu_name")] = row.Field<int>("Dedu_Amount");
}
}
var groupAjenda = ajenda.AsEnumerable().GroupBy(x => x.Field<int>("empID"));
foreach (var group in groupAjenda)
{
DataRow employeeRow = results.AsEnumerable().Where(x => x.Field<int>("empID") == group.Key).First();
foreach (DataRow row in group)
{
employeeRow[row.Field<string>("ajenda_name")] = row.Field<int>("ajenda_Amount");
}
}
}
}
}
Related
I would like to have two different counts in a single query; I wrote it with SQL Server with the COUNT function as
COUNT(CASE WHEN Status = 'opened' THEN 1 ELSE NULL)
which returns my desired count.
However, in the current situation, I have datatable and am not sure if the above two counts are possible in Linq.
My data is as below.
Email Status
------------------
email1 opened
email1 opened
email2 clicked
email2 clicked
email2 clicked
email1 clicked
email2 opened
The output needs to be:
Email Opened Clicked
-------------------------------
email1 2 1
email2 1 3
Using C# Linq try something like this:
var test = context.stats.GroupBy(x=> x.Email).Select(groupedBy=> new {
Email = groupedBy.FirstOrDefault().Email,
Opened = groupedBy.Where(y=> y.Status == "opened").Count(),
Clicked = groupedBy.Where(y=> y.Status == "clicked").Count()
});
You want a pivot table. See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication40
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Email", typeof(string));
dt.Columns.Add("Status", typeof(string));
dt.Rows.Add(new object[] { "email1", "opened"});
dt.Rows.Add(new object[] { "email1", "opened" });
dt.Rows.Add(new object[] { "email2", "clicked" });
dt.Rows.Add(new object[] { "email2", "clicked" });
dt.Rows.Add(new object[] { "email2", "clicked" });
dt.Rows.Add(new object[] { "email1", "clicked" });
dt.Rows.Add(new object[] { "email2", "opened" });
string[] statusTypes = dt.AsEnumerable().Select(x => x.Field<string>("Status")).Distinct().OrderBy(x => x).ToArray();
var groups = dt.AsEnumerable().GroupBy(x => x.Field<string>("Email")).ToList();
DataTable pivot = new DataTable();
pivot.Columns.Add("Email",typeof(string));
foreach(string statusType in statusTypes)
{
pivot.Columns.Add(statusType, typeof(int));
}
foreach(var group in groups)
{
DataRow row = pivot.Rows.Add();
row["Email"] = group.Key;
foreach(string statusType in statusTypes)
{
row[statusType] = group.Where(x => x.Field<string>("Status") == statusType).Count();
}
}
}
}
}
I'm new to C#. I know that datatable is very efficient for reading an entire SQL table and outputting data to griddataview. However I need to do some parsing before storing the data in my griddataview. I was thinking reading the table row by row and grouping the data when applicable. Would a datatable or a list be more applicable in my case?
ORIGINAL TABLE PARSED TABLE I need to pass to datagridview
Name Workdate Name M T W TH F SAT SUN
Nicole WED Nicole Y Y Y
Nicole THR Jason Y
Nicole MON
Jason Tue
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> dict = new Dictionary<string, string>() {
{"MON", "M"},{"TUE", "T"},{"WED", "W"},{"THR", "TH"},{"FRI", "F"},{"SAT", "SAT"},{"SUN", "SUN"}};
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Workdate", typeof(string));
dt.Rows.Add(new object[] { "Nicole", "WED" });
dt.Rows.Add(new object[] { "Nicole", "THR" });
dt.Rows.Add(new object[] { "Nicole", "MON" });
dt.Rows.Add(new object[] { "Jason", "TUE" });
DataTable pivot = new DataTable();
pivot.Columns.Add("Name",typeof(string));
DataColumn[] columns = dict.Select(x => new DataColumn(x.Value, typeof(string))).ToArray();
pivot.Columns.AddRange(columns);
var people = dt.AsEnumerable().GroupBy(x => x.Field<string>("Name")).ToArray();
foreach (var person in people)
{
DataRow pivotRow = pivot.Rows.Add();
pivotRow["Name"] = person.Key;
foreach (DataRow row in person)
{
string day = row.Field<string>("Workdate");
pivotRow[dict[day]] = "Y";
}
}
}
}
}
I am adding rows dynamically, as well as columns, into a datatable. The rows add as far as I can see, but as soon as I run the code nothing appears. It's like it's refreshing the table once the foreach loop finishes? Rookie question. Sorry.
summaryTable.Columns.Add("StationName", typeof(string));
summaryTable.Columns.Add("DepartmentCode", typeof(string));
var row = summaryTable.NewRow();
foreach (var item in issuesByClass)
{
row.SetField("StationName", item.StationName);
row.SetField("DepartmentCode", item.DepartmentCode);
foreach (var itemClass in item.Lookup)
{
if (!itemClassLookup.ContainsKey(itemClass.Key)) continue;
var itemClassValue = itemClassLookup[itemClass.Key];
// Ensure column hasn't been added before
if (!summaryTable.Columns.Contains(itemClassValue))
{
summaryTable.Columns.Add(itemClassValue, typeof(decimal));
}
row.SetField(itemClassValue, itemClass.Sum());
}
if (!summaryTable.Columns.Contains("GrandTotal"))
{
summaryTable.Columns.Add("GrandTotal", typeof(decimal));
}
row.SetField("GrandTotal", item.GrandTotal);
}
return summaryTable;
Small windows form app example:
public Form1()
{
this.InitializeComponent();
this.Test();
}
public void Test()
{
var dt = new DataTable();
var subs = new[] { "Sub 1", "Sub 2", "Sub 3" };
var row = dt.NewRow();
foreach (var sub in subs)
{
if (!dt.Columns.Contains("Subs"))
{
dt.Columns.Add("Subs");
}
row.SetField("Subs", sub);
}
dt.Columns.Add("Test");
row.SetField("Test", 1M);
this.dataGridView1.DataSource = dt;
}
NewRow() doesn't add the row. You need to do that manually at the bottom of the loop via .Rows.Add(row). You should also probably create the NewRow() per iteration.
foreach (var item in issuesByClass)
{
var row = summaryTable.NewRow();
// ...
summaryTable.Rows.Add(row);
}
I am using TemplateEngine.Docx, Template engine for generating Word docx
I am trying to MAP DataTable Result to Word Document Table, Below Code snippet is doing this by hard coding
var valuesToFill = new Content(
// Add table.
new TableContent("Team Members Table")
.AddRow(
new FieldContent("Name", "Eric"),
new FieldContent("Role", "Program Manager"))
.AddRow(
new FieldContent("Name", "Bob"),
new FieldContent("Role", "Developer")),
// Add field inside table that not to propagate.
new FieldContent("Count", "2")
);
I have Tried below code but I am not able to figure it out,
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("SOE_DT");
dt.Columns.Add("SOE_TM");
dt.Columns.Add("SOE_EV");
dt.Rows.Add(new object[] { "19/07/2017", "16:00", "This is First Event" });
dt.Rows.Add(new object[] { "19/07/2017", "16:30", "This is Second Event" });
dt.Rows.Add(new object[] { "19/07/2017", "17:00", "This is Third Event" });
dt.Rows.Add(new object[] { "19/07/2017", "18:00", "This is Fourth Event" });
TableContent tblSEQOfEvents = new TableContent("SEQOfEvents");
foreach (DataRow dtRow in dt.Rows)
{
//I Need to Add here tblSEQOfEvents.AddRow
foreach (DataColumn dc in dt.Columns)
{
tblSEQOfEvents.AddRow(
new FieldContent(dc.ColumnName, dtRow[dc].ToString()
));
}
}
The Result is showing in Image. I know that because of for each column loop it loops 12 times instead of 4 times I just show the snipped if some one help me to correct it.
Thanks
UPDATE 1
by This Stackoverflow Q/A I am able to get it done by following code, is it right way or it can me improve ?
foreach (DataRow dtRow in dt.Rows)
{
string SOE_DT = dtRow["SOE_DT"].ToString();
string SOE_TM = dtRow["SOE_TM"].ToString();
string SOE_EV = dtRow["SOE_EV"].ToString();
tblSEQOfEvents.AddRow(
new FieldContent("SOE_DT", SOE_DT),
new FieldContent("SOE_TM", SOE_TM),
new FieldContent("SOE_EV", SOE_EV)
);
}
TableContent.AddRow accepts IContentItem[]..
may be something like this..
foreach (DataRow dtRow in dt.Rows)
{
//I Need to Add here tblSEQOfEvents.AddRow
List<IContentItem> items = new List<IContentItem>();
foreach (DataColumn dc in dt.Columns)
{
items.Add(new FieldContent(dc.ColumnName, dtRow[dc].ToString()));
}
tblSEQOfEvents.AddRow(items.ToArray());
}
I have a table like this.
Date |Name |Id|Item |
23-March-2017|Vinod |1|USB |
02-May-2017 |Sureka|2|Cable |
23-March-2017|Mahesh|6|Mouse |
24-May-2017 |Raju |7|Keyboard|
09-May-2017 |Raju |2|Cable |
23-March-2017|Mahesh|6|Mouse |
02-May-2017 |Ganga |7|Keyboard|
I want get the Data according to Date in table Uisng LINQ Like
24-May-2017
Raju-Keyboard
09-May-2017
Raju-Cable
02-May-2017
Sureka-Cable
Ganga-Keyboard
23-March-2017
Vinod-USB
Mahesh-Cable
Mahesh-Mouse
context.Table.Select(o => new { Date = o.Date, Text = o.Name + "-" + o.Item }).GroupBy(o => o.Date);
Should do the trick, without me knowing you variable names and the like.
I recommend using a dictionary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication55
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Date", typeof (DateTime));
dt.Columns.Add("Name", typeof (string));
dt.Columns.Add("Id", typeof (int));
dt.Columns.Add("Item", typeof (string));
dt.Rows.Add(new object[] { DateTime.Parse("23-March-2017"), "Vinod", 1, "USB"});
dt.Rows.Add(new object[] { DateTime.Parse("02-May-2017"), "Sureka", 2, "Cable"});
dt.Rows.Add(new object[] { DateTime.Parse("23-March-2017"), "Mahesh",6, "Mouse"});
dt.Rows.Add(new object[] { DateTime.Parse("24-May-2017"), "Raju",7, "Keyboard"});
dt.Rows.Add(new object[] { DateTime.Parse("09-May-2017"), "Raju", 2, "Cable"});
dt.Rows.Add(new object[] { DateTime.Parse("23-March-2017"), "Mahesh", 6, "Mouse"});
dt.Rows.Add(new object[] { DateTime.Parse("02-May-2017"), "Ganga", 7, "Keyboard"});
Dictionary<DateTime, List<string>> dict = dt.AsEnumerable().GroupBy(x => x.Field<DateTime>("Date")).ToDictionary(x => x.Key, y => y.Select(z => z.Field<string>("Name") + "-" + z.Field<string>("Item")).ToList());
}
}
}