Updating fields after SubmitChanges in C# using foreach loops - c#

I have a project that I am working on, which is related to the work of daily shifts for employees, so that I have made the code for filling in the dates and their days in the relevant table ResultTB as follows and it's work correctly
var dt1 = DateTime.Parse(txtFromDate.Text);
var dt2 = DateTime.Parse(txtToDate.Text);
var dt = DateTime.Parse(txtFromDate.Text);
if (dt <= dt2)
{
dt = dt.AddDays(-1);
while (dt2 >= dt1)
{
List<ResultTB> ResultList = new List<ResultTB>
{
new ResultTB{NameOfDay = dt1.DayOfWeek.ToString(),DateOfDay = dt=dt.AddDays(1) }
};
foreach (var item in ResultList)
{
dt1 = dt1.AddDays(1);
db.ResultTBs.InsertOnSubmit(item);
}
db.SubmitChanges();
DGVResult.DataSource = db.ResultTBs.ToList();
}
}
Now I would like to make an update to the table ResultTB to columns EmpName+EmpID from EmployeeTB, so that the code searches in the table EmployeeTB which have the status of the employee “possible” and assigns it to a date in order, and this is the code that I wrote, but it adds the first person in the EmployeeTB table and assigns it to all the dates in the table ResultTB.
var EmpList = db.EmployeeTBs
.Where(x => x.EmpStatus == "possible").ToList();
foreach (var EmpItem in EmpList)
{
var ListOfResult = db.ResultTBs.Where(r => r.EmpName == null).ToList();
foreach (var itemResult in ListOfResult)
{
itemResult.EmpID = EmpItem.EmpID;
itemResult.EmpName = EmpItem.EmpName;
}
db.SubmitChanges();
}
I tried many solutions but it didn't work with me please help me to solve this problem. Thanks

var EmpList = db.EmployeeTBs.Where(x => x.EmpStatus == "possible").ToList();
for (int i=0; i< EmpList.length; i++)
{
var ListOfResult = db.ResultTBs.Where(r => r.EmpName == null).ToList();
ListOfResult[i].EmpID = EmpList[i].EmpID
ListOfResult[i].EmpName = EmpList[i].EmpName
}
db.SubmitChanges();
If I understood your question correctly this should work.

Related

How can I improve the performance of the following code?

This code is working but taking too much time. Every data table contains 1000nds of rows and each time I need to filter data from another data tables with respect to a column.
for (int i = 0; i < dsResult.Tables[0].Rows.Count; i++)
{
DataTable dtFiltered = dtWorkExp.Clone();
foreach (DataRow drr in dtWorkExp.Rows)
{
if (drr["UserId"].ToString() == dsResult.Tables[0].Rows[i]["Registration NO."].ToString())
{
dtFiltered.ImportRow(drr);
}
}
DataTable dtFilteredAward= dtAwards.Clone();
foreach (DataRow drr in dtAwards.Rows)
{
if (drr["UserId"].ToString() == dsResult.Tables[0].Rows[i]["Registration NO."].ToString())
{
dtFilteredAward.ImportRow(drr);
}
}
DataTable dtFilteredOtherQual = dtOtherQual.Clone();
foreach (DataRow drr in dtOtherQual.Rows)
{
if (drr["UserId"].ToString() == dsResult.Tables[0].Rows[i]["Registration NO."].ToString())
{
dtFilteredOtherQual.ImportRow(drr);
}
}
//Do some operation with filtered Data Tables
}
You can declare these lines outside the for loop.
DataTable dtFiltered = dtWorkExp.Clone();
And instead of doing accessing dsResult.Table[0] each time, you can assign this to one variable and use it.
You can also replace the foreach loop with LINQ.
What I would do:
All rows of the main datatable as enumerable:
var rows = dsResult.Tables[0].AsEnumerable();
Get the column you're going to filter with:
var filter = rows.Select(r => r.Field<string>("Registration NO."));
Create a method that accepts that filter, a table to filter and a field to compare.
public static DataTable Filter<T>(EnumerableRowCollection<T> filter, DataTable table, string fieldName)
{
return table.AsEnumerable().Where(r => filter.Contains(r.Field<T>(fieldName))).CopyToDataTable();
}
Finally use the method to filter all tables:
var dtFiltered = Filter<string>(filter, dtWorkExp, "UserId");
var dtFilteredAward = Filter<string>(filter, dtAwards, "UserId");
var dtFilteredOtherQual = Filter<string>(filter, dtOtherQual, "UserId");
All together woul be something like this
public void YourMethod()
{
var rows = dsResult.Tables[0].AsEnumerable();
var filter = rows.Select(r => r.Field<string>("Registration NO."));
var dtFiltered = Filter<string>(filter, dtWorkExp, "UserId");
var dtFilteredAward = Filter<string>(filter, dtAwards, "UserId");
var dtFilteredOtherQual = Filter<string>(filter, dtOtherQual, "UserId");
}
public static DataTable Filter<T>(EnumerableRowCollection<T> filter, DataTable table, string fieldName)
{
return table.AsEnumerable().Where(r => filter.Contains(r.Field<T>(fieldName))).CopyToDataTable();
}
Put the value of the expression in a variable.
var regNo = dsResult.Tables[0].Rows[i]["Registration NO."].ToString();
Put the index of column to the variable. Access by index more faster then by column name.
int index = dtWorkExp.Columns["UserId"].Ordinal;
Result code:
int dtWorkIndex = dtWorkExp.Columns["UserId"].Ordinal;
int dtAwardsIndex = dtAwards.Columns["UserId"].Ordinal;
int dtOtherQualIdex = dtOtherQual.Columns["UserId"].Ordinal;
for (int i = 0; i < dsResult.Tables[0].Rows.Count; i++)
{
var regNo = dsResult.Tables[0].Rows[i]["Registration NO."].ToString();
DataTable dtFiltered = dtWorkExp.Clone();
foreach (DataRow drr in dtWorkExp.Rows)
{
if (drr[dtWorkIndex].ToString() == regNo)
{
dtFiltered.ImportRow(drr);
}
}
...
Of course, the column index can be set as a constant if you know it exactly in advance. Also, if the UserId indexes match in all tables, a single variable is sufficient.
You can also try using the BeginLoadData and EndLoadData methods.
DataTable dtFiltered = dtWorkExp.Clone();
dtFiltered.BeginLoadData();
foreach (DataRow drr in dtWorkExp.Rows)
{
if (drr[dtWorkIndex].ToString() == regNo)
{
dtFiltered.ImportRow(drr);
}
}
dtFiltered.EndLoadData();
But I'm not sure if they make sense together with ImportRow.
Finally, parallelization comes to help.
for (int i = 0; i < dsResult.Tables[0].Rows.Count; i++)
{
var regNo = ...;
var workTask = Task.Run(() =>
{
DataTable dtFiltered = dtWorkExp.Clone();
foreach (DataRow drr in dtWorkExp.Rows)
{
if (drr[dtWorkIndex].ToString() == regNo)
{
dtFiltered.ImportRow(drr);
}
}
return dtFiltered;
});
var awardTask = Task.Run(() =>
...
var otherQualTask = Task.Run(() =>
...
//Task.WaitAll(workTask, awardTask, otherQualTask);
await Task.WhenAll(workTask, awardTask, otherQualTask);
//Do some operation with filtered Data Tables
}

Insert data from one sql table row to another where field matches - Entity Framework

I have two tables in an SQL database. They both have five fields: ID (PK), Number, InvoiceDate, InvoiceNumber, and InvoiceAmount. I am attempting to use Entity Framework to insert the InvoiceDate, InvoiceNumber, and InvoiceAmount where the field Number matches from one table to the other.
The context for table one is:
var tc = new TemporaryCsvUpload();
Table two:
var pt = new PermanentTestTable();
First, I inserted values into table 1 from a CSV, now I am trying to insert into table two where the Number field matches.
var entity = new CsvDbEntities1();
foreach (var item in model)
{
var tc = new TemporaryCsvUpload();
tc.Number = item.Number;
tc.CreditInvoiceAmount = item.CreditInvoiceAmount;
tc.CreditInvoiceDate = item.CreditInvoiceDate;
tc.CreditInvoiceNumber = item.CreditInvoiceNumber;
entity.TemporaryCsvUploads.Add(tc);
entity.SaveChanges();
}
I am new to EF and any help would be appreciated. Thanks!
Sorry if I dont completely understand but here it goes based of this code :
foreach (var item in model)
{
var tc = new TemporaryCsvUpload();
tc.Number = item.Number;
tc.CreditInvoiceAmount = item.CreditInvoiceAmount;
tc.CreditInvoiceDate = item.CreditInvoiceDate;
tc.CreditInvoiceNumber = item.CreditInvoiceNumber;
entity.TemporaryCsvUploads.Add(tc);
entity.SaveChanges();
}
After you have saved the first table now you query the second for the same record as :
var table2entity = entity.PermanentTestTable.Where(x => x.Number == tc.Number).Select(x => x).First();
This will query the second table and grab whatever entity is there with the same number
So your end code might look like :
var entity = new CsvDbEntities1();
foreach (var item in model)
{
var tc = new TemporaryCsvUpload();
tc.Number = item.Number;
tc.CreditInvoiceAmount = item.CreditInvoiceAmount;
tc.CreditInvoiceDate = item.CreditInvoiceDate;
tc.CreditInvoiceNumber = item.CreditInvoiceNumber;
entity.TemporaryCsvUploads.Add(tc);
entity.SaveChanges();
var table2entity = entity.PermanentTestTable.ToList();
table2entity = table2entity.Where(x => x.Number == tc.Number).Select(x => x).First();
table2entity.CreditInvoiceAmount = item.CreditInvoiceAmount;
//More values inserted here
entity.SaveChanges()
}
I ended up having to nest a foreach loop to iterate through every row with a Number field. I'm sure there is a better way to do this, but I am just happy it's working:
var entity = new CsvDbEntities1();
foreach (var item in model)
{
var tc = new TemporaryCsvUpload
{
PoNumber = item.Number,
CreditInvoiceAmount = item.CreditInvoiceAmount,
CreditInvoiceDate = item.CreditInvoiceDate,
CreditInvoiceNumber = item.CreditInvoiceNumber
};
entity.TemporaryCsvUploads.Add(tc);
var ptt = entity.PermanentTestTables.ToList().Where(x => x.Number == tc.Number);
foreach (var row in ptt)
{
row.CreditInvoiceDate = tc.CreditInvoiceDate;
row.CreditInvoiceNumber = tc.CreditInvoiceNumber;
row.CreditInvoiceAmount = tc.CreditInvoiceAmount;
}
entity.SaveChanges();
}

Use linq to find DataTable(Name) in a DataSet using unique list of Column Names

I got roped into some old code, that uses loose (untyped) datasets all over the place.
I'm trying to write a helper method to find the DataTable.Name using the names of some columns.....(because the original code has checks for "sometimes we have 2 datatables in a dataset, sometimes 3, sometimes 4)..and its hard to know the order. Basically, the TSQL Select statements conditionally run. (Gaaaaaaaaaaaaaahhh).
Anyway. I wrote the below, and if I give it 2 column names, its matching on "any" columnname, not "all column names".
Its probably my linq skillz (again), and probably a simple fix.
But I've tried to get the syntax sugar down..below is one of the things I wrote, that compiles.
private static void DataTableFindStuff()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable("TableOne");
dt1.Columns.Add("Table1Column11");
dt1.Columns.Add("Name");
dt1.Columns.Add("Age");
dt1.Columns.Add("Height");
DataRow row1a = dt1.NewRow();
row1a["Table1Column11"] = "Table1Column11_ValueA";
row1a["Name"] = "Table1_Name_NameA";
row1a["Age"] = "AgeA";
row1a["Height"] = "HeightA";
dt1.Rows.Add(row1a);
DataRow row1b = dt1.NewRow();
row1b["Table1Column11"] = "Table1Column11_ValueB";
row1b["Name"] = "Table1_Name_NameB";
row1b["Age"] = "AgeB";
row1b["Height"] = "HeightB";
dt1.Rows.Add(row1b);
ds.Tables.Add(dt1);
DataTable dt2 = new DataTable("TableTwo");
dt2.Columns.Add("Table2Column21");
dt2.Columns.Add("Name");
dt2.Columns.Add("BirthCity");
dt2.Columns.Add("BirthState");
DataRow row2a = dt2.NewRow();
row2a["Table2Column21"] = "Table2Column1_ValueG";
row2a["Name"] = "Table2_Name_NameG";
row2a["BirthCity"] = "BirthCityA";
row2a["BirthState"] = "BirthStateA";
dt2.Rows.Add(row2a);
DataRow row2b = dt2.NewRow();
row2b["Table2Column21"] = "Table2Column1_ValueH";
row2b["Name"] = "Table2_Name_NameH";
row2b["BirthCity"] = "BirthCityB";
row2b["BirthState"] = "BirthStateB";
dt2.Rows.Add(row2b);
ds.Tables.Add(dt2);
DataTable dt3 = new DataTable("TableThree");
dt3.Columns.Add("Table3Column31");
dt3.Columns.Add("Name");
dt3.Columns.Add("Price");
dt3.Columns.Add("QuantityOnHand");
DataRow row3a = dt3.NewRow();
row3a["Table3Column31"] = "Table3Column31_ValueM";
row3a["Name"] = "Table3_Name_Name00M";
row3a["Price"] = "PriceA";
row3a["QuantityOnHand"] = "QuantityOnHandA";
dt3.Rows.Add(row3a);
DataRow row3b = dt3.NewRow();
row3b["Table3Column31"] = "Table3Column31_ValueN";
row3b["Name"] = "Table3_Name_Name00N";
row3b["Price"] = "PriceB";
row3b["QuantityOnHand"] = "QuantityOnHandB";
dt3.Rows.Add(row3b);
ds.Tables.Add(dt3);
string foundDataTable1Name = FindDataTableName(ds, new List<string> { "Table1Column11", "Name" });
/* foundDataTable1Name should be 'TableOne' */
string foundDataTable2Name = FindDataTableName(ds, new List<string> { "Table2Column21", "Name" });
/* foundDataTable1Name should be 'TableTwo' */
string foundDataTable3Name = FindDataTableName(ds, new List<string> { "Table3Column31", "Name" });
/* foundDataTable1Name should be 'TableThree' */
string foundDataTableThrowsExceptionName = FindDataTableName(ds, new List<string> { "Name" });
/* show throw exception as 'Name' is in multiple (distinct) tables */
}
public static string FindDataTableName(DataSet ds, List<string> columnNames)
{
string returnValue = string.Empty;
DataTable foundDataTable = FindDataTable(ds, columnNames);
if (null != foundDataTable)
{
returnValue = foundDataTable.TableName;
}
return returnValue;
}
public static DataTable FindDataTable(DataSet ds, List<string> columnNames)
{
DataTable returnItem = null;
if (null == ds || null == columnNames)
{
return null;
}
List<DataTable> tables =
ds.Tables
.Cast<DataTable>()
.SelectMany
(t => t.Columns.Cast<DataColumn>()
.Where(c => columnNames.Contains(c.ColumnName))
)
.Select(c => c.Table).Distinct().ToList();
if (null != tables)
{
if (tables.Count <= 1)
{
returnItem = tables.FirstOrDefault();
}
else
{
throw new IndexOutOfRangeException(string.Format("FindDataTable found more than one matching Table based on the input column names. ({0})", String.Join(", ", columnNames.ToArray())));
}
}
return returnItem;
}
I tried this too (to no avail) (always has 0 matches)
List<DataTable> tables =
ds.Tables
.Cast<DataTable>()
.Where
(t => t.Columns.Cast<DataColumn>()
.All(c => columnNames.Contains(c.ColumnName))
)
.Distinct().ToList();
To me sounds like you're trying to see if columnNames passed to the method are contained within Column's name collection of Table. If that's the case, this should do the work.
List<DataTable> tables =
ds.Tables
.Cast<DataTable>()
.Where(dt => !columnNames.Except(dt.Columns.Select(c => c.Name)).Any())
.ToList();
(Below is an append by the asker of the question)
Well, I had to tweak it to make it compile, but you got me there..
Thanks.
Final Answer:
List<DataTable> tables =
ds.Tables.Cast<DataTable>()
.Where
(dt => !columnNames.Except(dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName))
.Any()
)
.ToList();
Final Answer (which is not case sensitive):
List<DataTable> tables =
ds.Tables.Cast<DataTable>()
.Where
(dt => !columnNames.Except(dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName), StringComparer.OrdinalIgnoreCase)
.Any()
)
.ToList();

Using attributes to find value linq

I’m a LINQ beginner and need some help. Below is the important part of the generated XML generated by a rest query.
<FormData FormOID="F_TABLEOFMODAL_V20" OpenClinica:Version="v2.0" OpenClinica:Status="initial data entry">
<ItemGroupData ItemGroupOID="IG_TABLE_MODALITYTABLE" ItemGroupRepeatKey="3" TransactionType="Insert">
<ItemData ItemOID="I_TABLE_MODAL_DATE_TABLE" Value="2014-04-10" />
<ItemData ItemOID="I_TABLE_MODAL_TYPE_TABLE" Value="4" />
</ItemGroupData>
<ItemGroupData ItemGroupOID="IG_TABLE_MODALITYTABLE" ItemGroupRepeatKey="1" TransactionType="Insert">
<ItemData ItemOID="I_TABLE_MODAL_DATE_TABLE" Value="2014-04-01" />
<ItemData ItemOID="I_TABLE_MODAL_TYPE_TABLE" Value="2" />
</ItemGroupData>
<ItemGroupData ItemGroupOID="IG_TABLE_MODALITYTABLE" ItemGroupRepeatKey="2" TransactionType="Insert">
<ItemData ItemOID="I_TABLE_MODAL_DATE_TABLE" Value="2014-04-04" />
<ItemData ItemOID="I_TABLE_MODAL_TYPE_TABLE" Value="1" />
</ItemGroupData>
</FormData>
What i want to get to are the ItemOIDs. My question is is there some way to get Values for all ItemOID="I_TABLE_MODAL_DATE_TABLE"(ans: two dates) and ItemOID="I_TABLE_MODAL_TYPE_TABLE" (ans: two numbers). The code below works but this uses ItemData for the first element (called date) and then skipping one to second element (type).
////Print out xml to use?
var doc = XDocument.Load(XmlReader.Create(streaming));
XNamespace nsSys = "http://www.cdisc.org/ns/odm/v1.3";
//loop through <ItemGroupData> to get both date and type value
//from each iteration
var items = from i in doc.Descendants(nsSys + "ItemGroupData")
select new
{
date = (string)i.Element(nsSys + "ItemData").Attribute("Value"),
type = (string)i.Descendants(nsSys + "ItemData").Skip(1).First().Attribute("Value")
};
//Catch here?
DataTable modDt = new DataTable();
modDt.Columns.Add(new DataColumn("Date", typeof(string)));
modDt.Columns.Add(new DataColumn("Type", typeof(string))); //changed to string?
//add LINQ-to-XML query result to DataTable
foreach (var item in items)
{
//convert item.date string to DateTime
//then convert it back to string with different format
modDt.Rows.Add(DateTime.ParseExact(item.date, "yyyy-MM-dd", CultureInfo.InvariantCulture)
.ToString("MM/dd/yy"),
int.Parse(item.type));
}
//Value of OC output
//1=mr,2=ct,3=pet,4=us,5=meg,6=ecg (put if statements before xnat rest ssh string)
for (int i = 0; i <= modDt.Rows.Count - 1; i++)
{
modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("1", "mr");
modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("2", "ct");
modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("3", "pet");
modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("4", "us");
modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("5", "meg");
modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("6", "ecg");
}
I've started writting some code shown below. The adding of data into datatable still does not work sorry. However the idea of what i'm trying to do is in there.
DataTable modDt = new DataTable();
modDt.Columns.Add(new DataColumn("Date", typeof(string)));
modDt.Columns.Add(new DataColumn("Type", typeof(string))); //changed to string?
var document = XDocument.Load("doc.xml");
XNamespace nsSys = "http://www.cdisc.org/ns/odm/v1.3";
//Get nodes separated by inner child element
var itd = document.Descendants(nsSys + "ItemData")
.Where(t => (string)t.Attribute("ItemOID") == "I_TABLE_MODAL_DATE_TABLE");
var itds = itd.Attributes("Value").ToArray();
foreach (var it in itds)
{
var subA = it.ToString();
var subAA = subA.ToCharArray();
var subB = subAA.Skip(9).Take(8).ToArray();
string sub = new string(subB);
var subBB = sub.Split('-').ToArray();
string subC = subBB[1] + "/" + subBB[2] + "/" + subBB[0];
foreach (DataRow dr in modDt.Rows)
{
dr["Date"] = subC;
}
Console.WriteLine(subC);
}
var itt = document.Descendants(nsSys + "ItemData")
.Where(t => (string)t.Attribute("ItemOID") == "I_TABLE_MODAL_TYPE_TABLE");
var itty = itt.Attributes("Value").ToArray();
foreach (var et in itty)
{
var subz = et.ToString();
var subzz = subz.ToCharArray();
var subx = subzz.Skip(7).Take(1).ToArray();
string subxx = new string(subx);
foreach (DataRow dt in modDt.Rows)
{
dt["Type"] = subxx;
}
Console.WriteLine(subxx);
}
//for (int i = 0; i <= modDt.Rows.Count - 1; i++)
//{
// modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("1", "mr");
// modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("2", "ct");
// modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("3", "pet");
// modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("4", "us");
// modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("5", "meg");
// modDt.Rows[i][1] = modDt.Rows[i][1].ToString().Replace("6", "ecg");
//}
foreach (DataRow row in modDt.Rows) // Loop over the rows.
{
string sessionDate = row["Date"].ToString();
string mod = row["Type"].ToString();
string drow = "aa" + sessionDate + "bb" + mod + "cc";
Console.WriteLine(drow);
}
Console.Read();
Thank you so much for your help and your time. It is greatly appreciated. Cheers.
Current Attempt
DataTable modDt = new DataTable();
modDt.Columns.Add(new DataColumn("Date", typeof(string)));
modDt.Columns.Add(new DataColumn("Type", typeof(string))); //changed to string?
var document = XDocument.Load("doc.xml");
XNamespace nsSys = "http://www.cdisc.org/ns/odm/v1.3";
//Get nodes separated by inner child element
var values = document.Descendants(nsSys + "ItemData")
.Where(t => t.Attribute("ItemOID").Value == "I_TABLE_MODAL_DATE_TABLE")
.Select(x => x.Attribute("Value").Value);
foreach (var item in values)
{
modDt.Rows.Add(DateTime.ParseExact(item, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MM/dd/yy"),null);
}
var typevalues = document.Descendants(nsSys + "ItemData")
.Where(t => t.Attribute("ItemOID").Value == "I_TABLE_MODAL_TYPE_TABLE")
.Select(x => x.Attribute("Value").Value);
foreach (var item in typevalues)
{
modDt.Rows.Add(null ,int.Parse(item));
}
foreach (DataRow row in modDt.Rows)
{
string sessionDate = row["Date"].ToString();
string mod = row["Type"].ToString();
string xnatCli = mod + sessionDate;
Console.Write(xnatCli);
}
i am trying to answer your question in a single line of code
var values = document.Descendants("ItemData")
.Where(t => t.Attribute("ItemOID").Value == "I_TABLE_MODAL_DATE_TABLE")
.Select(x => x.Attribute("Value").Value)
after this line the values collection will have all the dates. same can be applied to other queries as well.
Update: the solution below use linq to sql, assuming class FormDataContext is prepared for connecting database to relevant table.
FormDataContext db = new FormDataContext();
[Table(Name = "FormData")]
public class FormData
{
[Column]
public DateTime Date;
[Column]
public int Type;
}
IEnumerable<FormData> values = document.Descendants("ItemGroupData").Select(t => {
return new FormData {
FormDate = Convert.ToDateTime(t.XPathSelectElement("ItemData[#ItemOID='I_TABLE_MODAL_DATE_TABLE']").Attribute("Value").Value),
Type = Convert.ToInt32(t.XPathSelectElement("ItemData[#ItemOID='I_TABLE_MODAL_TYPE_TABLE']").Attribute("Value").Value)
};
});
foreach (FormData data in values) {
db.Form.InsertOnSubmit(data);
}
db.SubmitChanges();
This is just an example to store the required two fields to db. You may adjust the example based on your needs.

how convert DataTable to List<String> in C#

I am using C# Linq now I am converting DataTable to List
and I am getting stuck...
give me right direction thanks..
private void treeview1_Expanded(object sender, RoutedEventArgs e)
{
coa = new List<string>();
//coa = (List<string>)Application.Current.Properties["CoAFull"];
HMDAC.Hmclientdb db = new HMDAC.Hmclientdb(HMBL.Helper.GetDBPath());
var data = (from a in db.CoA
where a.ParentId == 0 && a.Asset == true
select new { a.Asset, a.Category, a.CoAName, a.Hide, a.Recurring, a.TaxApplicable });
DataTable dtTable = new DataTable();
dtTable.Columns.Add("Asset", typeof(bool));
dtTable.Columns.Add("Category", typeof(string));
dtTable.Columns.Add("CoAName", typeof(string));
dtTable.Columns.Add("Hide", typeof(bool));
dtTable.Columns.Add("Recurring", typeof(bool));
dtTable.Columns.Add("TaxApplicable", typeof(bool));
if (data.Count() > 0)
{
foreach (var item in data)
{
DataRow dr = dtTable.NewRow();
dr["Asset"] = item.Asset;
dr["Category"] = item.Category;
dr["CoAName"] = item.CoAName;
dr["Hide"] = item.Hide;
dr["Recurring"] = item.Recurring;
dr["TaxApplicable"] = item.TaxApplicable;
dtTable.Rows.Add(dr);
}
}
coa = dtTable;
}
It seems that you already have a strongly typed list. Why converting this to a weakly typed DataTable and then back to a list?????
var data =
from a in db.CoA
where a.ParentId == 0 && a.Asset == true
select new
{
a.Asset,
a.Category,
a.CoAName,
a.Hide,
a.Recurring,
a.TaxApplicable
};
var list = data.ToList();
If you want to be able to use this list outside the scope of the method, define a type that will hold the different properties and in your select statement use this type instead of the anonymous type like:
var data =
from a in db.CoA
where a.ParentId == 0 && a.Asset == true
select new MyType
{
Asset = a.Asset,
Category = a.Category,
CoAName = a.CoAName,
Hide = a.Hide,
Recurring = a.Recurring,
TaxApplicable = a.TaxApplicable
};
List<MyType> list = data.ToList();
You don't need the data table according to the code you have displayed:
var data = (from a in db.CoA
where a.ParentId == 0 && a.Asset == true
select new { a.Asset.ToString() + a.Category.ToString()
+ a.CoAName.ToString()... }).ToList();
If you really want to convert your datatable to a 1D list, you can do it like this
foreach (DataRow row in dtTable.Rows)
{
foreach (DataColumn col in dtTable.Columns)
{
coa.Add(row[col]);
}
}
As you are using Select new in you linq query It will find object. What you can do is
var data = (from a in db.CoA
where a.ParentId == 0 && a.Asset == true
select new { a.Asset, a.Category, a.CoAName, a.Hide, a.Recurring, a.TaxApplicable });
this is your query and you select multiple columns in your query. So you can't convert your data to a single List of string. What you can do is concatenate all the column in a single string and then add them in a list of string.
To do that modify your query like 'CK' said
var data = (from a in db.CoA
where a.ParentId == 0 && a.Asset == true
select new { a.Asset.ToString() + a.Category.ToString()
+ a.CoAName.ToString()... }).ToList();
And then do
List<string> name = new List<string>(data.ToList());

Categories

Resources