Datatable modify column with row - c#

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:

Related

Processing lambda query result in C# after performing table join

So I have a query that joins two data tables together:
var results = (
from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on
new { a = t1["col1"], b= t1["col2"], c = t1["col3"] } equals
new { a= t2["col1"], b= t2["col2"], c= t2["col3"] }
into joinedComboTable
select joinedComboTable);
and it produces a result whose type is IEnumerable<IEnumerable<datarow>>"
How am I to convert that to a DataTable? Tables 1 and Tables 2 are C# DataTables. I do see 304 results which I can see through the debugger and the results.inner (Non-Public) parameter that I have DataColumns and I can see 304 rows. But am unable to figure out how to get to actual result and have it saved into a DataTable.
UPDATE: 2020.01.23 # 9:04pm
So, I checked out a couple options below and when I perform a results.ToList(), I get basically a list of 304 entries, but each row value is System.Data.DataRow[0]. I must be missing something....
Iterating over this doesn't produce the desired results.
Try This
static void Main(string[] args)
{
var table1 = new DataTable();
table1.Columns.Add("col1", typeof(string));
table1.Columns.Add("col2", typeof(string));
table1.Columns.Add("col3", typeof(string));
table1.Columns.Add("col4", typeof(string));
var row = table1.NewRow();
row["col1"] = "1";
row["col2"] = "1";
row["col3"] = "1";
row["col4"] = "something different";
table1.Rows.Add(row);
row = table1.NewRow();
row["col1"] = "2";
row["col2"] = "2";
row["col3"] = "2";
row["col4"] = "something different";
table1.Rows.Add(row);
var table2 = new DataTable();
table2.Columns.Add("col1", typeof(string));
table2.Columns.Add("col2", typeof(string));
table2.Columns.Add("col3", typeof(string));
table2.Columns.Add("col4", typeof(string));
row = table2.NewRow();
row["col1"] = "1";
row["col2"] = "1";
row["col3"] = "1";
row["col4"] = "Another different thing";
table2.Rows.Add(row);
var results = (
from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on
new { a = t1["col1"], b = t1["col2"], c = t1["col3"] } equals
new { a = t2["col1"], b = t2["col2"], c = t2["col3"] }
into joinedComboTable
select joinedComboTable).ToList();
//Result
var newTable = results.FirstOrDefault()?.CopyToDataTable();
//However to get col4 form table 2 you need to do this
var result2 = (
from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on
new { a = t1["col1"], b = t1["col2"], c = t1["col3"] } equals
new { a = t2["col1"], b = t2["col2"], c = t2["col3"] }
select new { a = t1["col1"], b = t1["col2"], c = t1["col3"], d = t1["col4"], e = t2["col4"] });
//Result
var newTable2 = table1.Clone();
newTable2.Columns.Add("col4FromTable2", typeof(string));
foreach (var x1 in result2)
{
var r = newTable2.NewRow();
r["col1"] = x1.a;
r["col2"] = x1.b;
r["col3"] = x1.c;
r["col4"] = x1.d;
r["col4FromTable2"] = x1.e;
newTable2.Rows.Add(r);
}
}
You can get the first level by calling var rows = result.FirstOrDefault() to return an IEnumerable of rows. Create a new instance of the data table var newtable = new DataTable(); then loop through to add the rows to the rows collection property of the new data table like so...
for(var i=0; i <= rows.Count(); i++)
newtable.Rows.Add(rows[i]);
something like this should work for you.
Sorry for the typo.. I'm using my mobile phone

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);

LINQ only sum rows if columns totaled is not zero

Given the following rows:
Amount, Name, Id
Scenario 1: 100.00,ABC,101
-100.00,ABC,101
Scenario 2: 50.00,XYZ,123
-100.00,XYZ,123
I want to sum and group the rows only if the the amount does not totaled to 0.00 amount. So the Linq query should return this:
Amount, Name, Id
Scenario 1: 100.00,ABC,101
-100.00,ABC,101
Scenario 2:-50.00,XYZ,123
What I have so far:
var results = dt.AsEnumerable().GroupBy(row => new
{
Name = row.Field<string>("NAME"),
Id = row.Field<int>("ID")
}).Select(grp =>
{
DataRow dr = dt.NewRow();
dr["AMOUNT"] = grp.Sum(r => r.Field<decimal>("AMOUNT"));
dr["NAME"] = grp.Key.Name;
dr["ID"] = grp.Key.Id;
return dr;
}).CopyToDataTable();
You could try the following query using SelectMany extension method:
var query= dt.AsEnumerable().GroupBy(row => new
{
Name = row.Field<string>("NAME"),
Id = row.Field<int>("ID")
})
.SelectMany(grp=>
{
var sum=grp.Sum(r => r.Field<decimal>("AMOUNT");
if(sum!=0)
{
DataRow dr = dt.NewRow();
dr["AMOUNT"] = sum;
dr["NAME"] = grp.Key.Name;
dr["ID"] = grp.Key.Id;
return dr;
}
else
{
return grp;
}
}).CopyToDataTable();
It's difficult to understand what you're asking, so I'm assuming that you mean:
Sum and group rows, so only a single summarised transaction is listed for any given ID, unless the total is zero, then list all of the transactions for that ID.
Here's a working example, with the test data you provided:
var amounts = new[]
{
new
{
Amount = 100.00m,
Name = "ABC",
Id = 101,
},
new
{
Amount = -100.00m,
Name = "ABC",
Id = 101,
},
new
{
Amount = 50.00m,
Name = "XYZ",
Id = 123,
},
new
{
Amount = -100.00m,
Name = "XYZ",
Id = 123,
},
};
// summarise everything
var summaries = from a in amounts
group a by new { a.Id, a.Name } into grouping
select new
{
Amount = grouping.Sum(g => g.Amount),
grouping.Key.Name,
grouping.Key.Id,
};
// get the ids of records we need the full audit log for
var zeroSummaries = summaries.Where(s => s.Amount == 0).Select(s => s.Id).ToList();
// concat the summarised records together with the ones we need the full audit log for
summaries = amounts.Where(a => zeroSummaries.Contains(a.Id))
.Concat(summaries.Where(s => s.Amount != 0));
Here's the output:

DataTable group the result in one row

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);
}

Categories

Resources