DataTable group the result in one row - c#

I have a DataTable and want to group Name, LastName and Comment. The rest should be in the same row.
In my Code firstly i make ID's values as header and then organize the Attribute values to each ID. What I want here is to group the the same Name, Lastname and Comment with their ID values.
My first Table looks like that:
ID Name Lastmame Comment Attribute
1 kiki ha hello FF
3 lola mi hi AA
2 ka xe what UU
2 kiki ha hello SS
After I use my code:
Name Lastname Comment 1 3 2
kiki ha hello FF
lola mi hi AA
ka xe what UU
kiki ha hello SS
What I want to have is:
Name Lastname Comment 1 3 2
kiki ha hello FF SS
lola mi hi AA
ka xe what UU
My Code:
DataTable table1 = new DataTable("Kunde");
table1.Columns.Add("Comment", typeof(String));
table1.Columns.Add("Name", typeof(String));
table1.Columns.Add("Lastname", typeof(String));
DataTable comment = new DataTable("Comment");
comment.Columns.Add("ID", typeof(String));
comment.Columns.Add("Comment", typeof(String));
comment.Columns.Add("Attribute", typeof(String));
DataSet ds = new DataSet("DataSet");
ds.Tables.Add(table1);
ds.Tables.Add(comment);
object[] o1 = { "hello", "kiki", "ha" };
object[] o2 = { "hi", "lola", "mi" };
object[] o3 = { "what", "ka", "xe" };
object[] c1 = { 1, "hello", "FF" };
object[] c2 = { 3, "hi", "AA" };
object[] c3 = { 2, "what", "UU" };
object[] c4 = { 2, "hello", "SS" };
table1.Rows.Add(o1);
table1.Rows.Add(o2);
table1.Rows.Add(o3);
comment.Rows.Add(c1);
comment.Rows.Add(c2);
comment.Rows.Add(c3);
comment.Rows.Add(c4);
var results = from tb1 in comment.AsEnumerable()
join tb2 in table1.AsEnumerable()
on tb1.Field<string>("Comment") equals tb2.Field<string>("Comment")
select new
{
ID = tb1.Field<String>("ID"),
Name = tb2.Field<String>("Name"),
Lastname = tb2.Field<String>("Lastname"),
Comment = tb1.Field<String>("Comment"),
Attribute = tb1.Field<String>("Attribute"),
};
DataTable result = LINQToDataTable(results);
var products = result.AsEnumerable()
.GroupBy(c => c["ID"])
.Where(g => !(g.Key is DBNull))
.Select(g => (string)g.Key)
.ToList();
var newtable = result.Copy();
products.ForEach(p => newtable.Columns.Add(p, typeof(string)));
foreach (var row in newtable.AsEnumerable())
{
if (!(row["ID"] is DBNull)) row[(string)row["ID"]] = row["Attribute"];
}
newtable.Columns.Remove("ID");
newtable.Columns.Remove("Attribute");
var result11 = from t1 in newtable.AsEnumerable()
group t1 by new { Name = t1.Field<String>("Name"), LastName = t1.Field<String>("LastName"), Comment = t1.Field<String>("Comment"), } into grp
select new
{
Name = grp.Key.Name,
LastName = grp.Key.LastName,
Comment = grp.Key.Comment,
//Something here
};
LINQToDataTable method definition
using System.Reflection;
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}

Based on the comments to this other answer:
One approach would be to stuff all the variable columns in a structure (like a dictionary).
In order to do this, use the following query:
var variableColumnNames = newtable.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.Except(new[]{"Name", "Lastname", "Comment"});
var result11 = from t1 in newtable.AsEnumerable()
group t1 by new
{
Name = t1.Field<String>("Name"),
LastName = t1.Field<String>("LastName"),
Comment = t1.Field<String>("Comment"),
} into grp
select new
{
grp.Key.Name,
grp.Key.LastName,
grp.Key.Comment,
Values = variableColumnNames.ToDictionary(
columnName => columnName,
columnName => grp.Max(r => r.Field<String>(columnName)))
};
If you really need to have a variable number of properties in the class, this is not possible as far as I know, so the only plausible way to do that is to output the result to another DataTable (to which we can add as many columns as we want).
Approach #2 - using dynamic
The LINQ query:
var result11 = from t1 in newtable.AsEnumerable()
group t1 by new
{
Name = t1.Field<String>("Name"),
LastName = t1.Field<String>("LastName"),
Comment = t1.Field<String>("Comment"),
} into grp
select CreateNewDynamicObject
(
grp.Key.Name,
grp.Key.LastName,
grp.Key.Comment,
variableColumnNames.ToDictionary(
columnName => columnName,
columnName => grp.Max(r => r.Field<String>(columnName)))
);
}
the new method that creates the dynamic object:
private static dynamic CreateNewDynamicObject(
string name, string lastName, string comment, Dictionary<string, string> customProperties)
{
dynamic obj = new ExpandoObject();
obj.Name = name;
obj.LastName = lastName;
obj.Comment = comment;
foreach (var prop in customProperties)
(obj as IDictionary<string, Object>).Add(prop.Key, prop.Value ?? "");
return obj;
}
Approach #3 - outputting to a DataTable
The resulting DataTable (destinationTable) can be used as a source for a DataGridView:
var destinationTable = new DataTable();
foreach (var column in newtable.Columns.Cast<DataColumn>())
destinationTable.Columns.Add(column.ColumnName, typeof(String));
var result11 =
from t1 in newtable.AsEnumerable()
group t1 by new
{
Name = t1.Field<String>("Name"),
LastName = t1.Field<String>("Lastname"),
Comment = t1.Field<String>("Comment"),
}
into grp
select
variableColumnNames.ToDictionary(
columnName => columnName,
columnName => grp.Max(r => r.Field<String>(columnName)))
.Concat(new Dictionary<string, string>
{
{"Name", grp.Key.Name},
{"Lastname", grp.Key.LastName},
{"Comment", grp.Key.Comment}
}
).ToDictionary(x => x.Key, x => x.Value);
foreach (var row in result11)
{
var newRow = destinationTable.NewRow();
foreach (var columnName in newtable.Columns.Cast<DataColumn>().Select(c => c.ColumnName))
newRow[columnName] = row[columnName];
destinationTable.Rows.Add(newRow);
}

Related

How to join 2 data tables

DataTable1
LoginId LoginName SCount
1 Mohit 20
3 Riya 25
DataTable2
LoginId LoginName ECount
2 Smita 11
3 Riya 13
I want to show result like this
LoginName Scount Ecount Total
Mohit 20 0 20
Smita 0 11 11
Riya 25 13 38
Query:
DataTable dtResult = new DataTable();
DataTable UserCount1 = new DataTable();
DataTable UserCount2 = new DataTable();
// Assigning value to datatable
if (ds != null)
{
UserCount1 = ds.Tables["UserCount1"];
UserCount2 = ds.Tables["UserCount2"];
}
var LinqResult =
from dataRows1 in UserCount1.AsEnumerable()
join dataRows2 in UserCount2.AsEnumerable()
on dataRows1.Field<string>("LoginId") equals dataRows2.Field<string>("LoginId") into lj
from r in lj.DefaultIfEmpty()
select dtResult.LoadDataRow(new object[]
{
dataRows2.Field<string>("LoginName"),
r == null ? 0 : r.Field<int>("SCount"),
r == null ? 0 : r.Field<int>("ECount")
}, false);
Getting complie time error in
select statement( dataRows2.Field<string>("LoginName"),)
that dataRows2 does not exist in current context.
How to achieve that result?
For the easy and strongly typed solution, I would strongly suggest defining classes, such as:
class User1 { public int LoginId; public string LoginName; public int SCount; }
class User2 { public int LoginId; public string LoginName; public int ECount; }
to enable LINQ extension methods, then your task becomes quite easy (explanation in comments in code):
// Sample data.
DataTable UserCount1 = new DataTable();
DataTable UserCount2 = new DataTable();
UserCount1.Columns.AddRange(new DataColumn[] { new DataColumn("LoginId"), new DataColumn("LoginName"), new DataColumn("SCount") });
UserCount2.Columns.AddRange(new DataColumn[] { new DataColumn("LoginId"), new DataColumn("LoginName"), new DataColumn("ECount") });
UserCount1.Rows.Add(1, "Mohit", 20);
UserCount1.Rows.Add(3, "Riya", 25);
UserCount2.Rows.Add(2, "Smita", 31);
UserCount2.Rows.Add(3, "Riya", 13);
// Here we create lists of our users.
List<User1> users1 = new List<User1>();
List<User2> users2 = new List<User2>();
foreach (DataRow row in UserCount1.Rows)
users1.Add(new User1() { LoginId = int.Parse(row["LoginId"].ToString()), LoginName = (string)row["LoginName"], SCount = int.Parse(row["SCount"].ToString()) });
foreach (DataRow row in UserCount2.Rows)
users2.Add(new User2() { LoginId = int.Parse(row["LoginId"].ToString()), LoginName = (string)row["LoginName"], ECount = int.Parse(row["ECount"].ToString()) });
// Full outer join: first we join, then add entries, that were not included.
var result = users1.Join(users2, u1 => u1.LoginId, u2 => u2.LoginId, (u1, u2) => new { LoginId = u1.LoginId, LoginName = u1.LoginName, SCount = u1.SCount, ECount = u2.ECount, Total = u1.SCount + u2.ECount }).ToList();
result.AddRange(users1.Where(u1 => !result.Select(u => u.LoginId).Contains(u1.LoginId)).Select(u1 => new { LoginId = u1.LoginId, LoginName = u1.LoginName, SCount = u1.SCount, ECount = 0, Total = u1.SCount }));
result.AddRange(users2.Where(u2 => !result.Select(u => u.LoginId).Contains(u2.LoginId)).Select(u2 => new { LoginId = u2.LoginId, LoginName = u2.LoginName, SCount = 0, ECount = u2.ECount, Total = u2.ECount }));
Then you can construct another result DataTable, for which I don't see any reason.

How can use dynamic columns in linq?

how can i use dynamic columns instead of this query
id = row.Field<int>("id") ,
rec_date = row.Field<string>("rec_date")
var result = from row in dt.AsEnumerable()
group row by new
{
id = row.Field<int>("id") ,
rec_date = row.Field<string>("rec_date")
} into section1
select new
{
section1.Key.id,
section1.Key.rec_date,
children = from l2 in section1
select new
{
tax_rate = l2.Field<string>("tax_rate"),
tax_amount = l2.Field<string>("tax_amount")
}
};
var jsonString = JsonConvert.SerializeObject(result);

Column referenced is not in scope: ''

Hallo I'm still newbie in linq and programming
I'm trying to make a report using crystal report with linq query and to put it into datatable I'm using function that throw, but got Column referenced is not in scope: ''..
I'm trying to joining 3 tables.
this is a function that I've found from internet
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
and here is my linq
var id = (from u in myDb.TBL_TRANSAKSI_MKN_MNMs
join l in myDb.TBL_DETAIL_TRANSAKSIs on u.ID_NOTA equals l.ID_NOTA
//into g1
join m in myDb.TBL_MKN_MNMs on l.ID_MKN_MNM equals m.ID_MKN_MNM
//into g
group new {u,l,m} by new {u.TGL_TRANSAKSI, m.NAMA_MKN_MNM, m.HARGA_JUAL, l.ID_MKN_MNM, u.USERNAME}
into grp
where grp.Key.TGL_TRANSAKSI.Value.Date.Equals(dateTimePicker1.Value.Date)
select new
{
MakanMinum = grp.Key.NAMA_MKN_MNM,
HargaJual = grp.Key.HARGA_JUAL,
sumStok = grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM),
Tanggal = grp.Key.TGL_TRANSAKSI,
Jumlah = grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM),
Total = grp.Sum(grouptotal => grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM)),
Username = grp.Key.USERNAME
});
I've got a throw in line foreach (T rec in varlist)
is there any simple query..?? because I'm confuse to join 3 tables...
thank you for the advance
I think your problems is:
your query result is anonymous type ,so you should change your code like this:
var id = (from u in myDb.TBL_TRANSAKSI_MKN_MNMs
where u.GL_TRANSAKSI.Value.Date.Equals(dateTimePicker1.Value.Date)
join l in myDb.TBL_DETAIL_TRANSAKSIs on u.ID_NOTA equals l.ID_NOTA
//into g1
join m in myDb.TBL_MKN_MNMs on l.ID_MKN_MNM equals m.ID_MKN_MNM
//into g
group new {u,l,m} by new {u.TGL_TRANSAKSI, m.NAMA_MKN_MNM, m.HARGA_JUAL, l.ID_MKN_MNM, u.USERNAME}
into grp
select new MyClass
{
MakanMinum = grp.Key.NAMA_MKN_MNM,
HargaJual = grp.Key.HARGA_JUAL,
sumStok = grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM),
Tanggal = grp.Key.TGL_TRANSAKSI,
Jumlah = grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM),
Total = grp.Sum(grouptotal => grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM)),
Username = grp.Key.USERNAME
});
class MyClass
{
public string MakanMinum {get;set;}
.....
}

Reversing typeof to use Linq Field<T>

I want to use Linq to dynamically select DataTable columns by ColumnName but to use Field<> I must explicitly cast them or box everything to an object, which is not efficient.
I tried:
string[] colsNames = new[] { "Colum1", "Colum2" };
DataTable dt = StoredProcedure().Tables[0];
var cols = dt.Columns.Cast<DataColumn>().Where(c => cols.Contains(c.ColumnName));
if (cols.Any())
{
dt.AsEnumerable().Select(r => string.Join(":", cols.Select(c => r.Field<c.DataType>(c.ColumnName))))
}
but this throws me an error The type or namespace name 'c' could not be found
How do I convert typeof(decimal) to Field<decimal>("Column1") for example?
Try this:
DataTable dt = new DataTable();
dt.Columns.Add("id", Type.GetType("System.Int32"));
dt.Columns.Add("Colum1", Type.GetType("System.Int32"));
dt.Columns.Add("Colum2", Type.GetType("System.String"));
dt.Columns.Add("Colum3");
string[] colsNames = new[] { "Colum1", "Colum2" };
var colTypes = dt.Columns.Cast<DataColumn>()
.Where(c => colsNames.Contains(c.ColumnName))
.Select(c => new
{
c.ColumnName,
c.DataType
})
.ToDictionary(key => key.ColumnName, val => val.DataType);
var query = dt.AsEnumerable()
.Where(row => (int)row["id"]==5)
.Select(row => new
{
Colum1 = Convert.ChangeType(row[colsNames[0]], colTypes[colsNames[0]]),
Colum2 = Convert.ChangeType(row[colsNames[1]], colTypes[colsNames[1]])
});
Here is another variant, but it is not very interesting:
//define class
public class myClass
{
public int Column1;
public string Column2;
}
// then
var query = dt.AsEnumerable()
.Select(row => new myClass
{
Column1 = Convert.ToInt32(row[colsNames[0]]),
Column2 = row[colsNames[1]].ToString()
});
There is a third variant: you can create a view or stored procedure in the database and add it to the data context

Datatable modify column with row

I want to modify my table in a Datatable. I know that I have to use linq and group the results.
Before:
ID Name LastName
1 Kiki ha
3 lola mi
2 ka xe
2 Kiki ha
After:
Name LastName 1 3 2
Kiki ha x x
lola mi x
ka xe x
My original code:
DataTable table1 = new DataTable("table");
table1.Columns.Add("ID", typeof(String));
table1.Columns.Add("Name", typeof(String));
table1.Columns.Add("Lastname", typeof(String));
object[] a1 = { 1, "Kiki", "ha" };
object[] a2 = { 3, "lola", "mi" };
object[] a4 = { 2, "ka", "xe" };
object[] a5 = { 2, "kiki", "ha" };
table1.Rows.Add(a1);
table1.Rows.Add(a2);
table1.Rows.Add(a4);
table1.Rows.Add(a5);
I also tried this but it didn't work:
var result = from t1 in table1.AsEnumerable()
group t1 by new {ID = t1.Field<String>("ID")} into grp
select new
{
ID = grp.Key.ID,
//something must be there
};
DataGridView1.DataSource = result.ToList();
This should do what you need:
var nameGroups = from row in table1.AsEnumerable()
group row by new
{
Name = row.Field<string>("Name").ToLower(),
LastName = row.Field<string>("Lastname").ToLower(),
} into NameGroups
select NameGroups;
var tblOut = new DataTable();
tblOut.Columns.Add("Name");
tblOut.Columns.Add("LastName");
var distinctIDs = table1.AsEnumerable()
.Select(r => r.Field<string>("ID"))
.Distinct();
foreach (var id in distinctIDs)
tblOut.Columns.Add(id);
foreach (var grp in nameGroups)
{
var row = tblOut.Rows.Add();
row.SetField<string>("Name", grp.Key.Name);
row.SetField<string>("LastName", grp.Key.LastName);
foreach (DataColumn idCol in tblOut.Columns.Cast<DataColumn>().Skip(2))
{
bool userHasID = grp.Any(r => r.Field<string>("ID") == idCol.ColumnName);
row.SetField<string>(idCol, userHasID ? "x" : "");
}
}
Note that i output the lowercase names because i needed to group by case insensitive.
Edit: Here's a screenshot of the DataTable in the debugger window:

Categories

Resources