我现在正在使用C#Linq我将DataTable转换为List 我被困了...... 给我正确的方向谢谢..
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;
}
答案 0 :(得分:4)
您似乎已经拥有了一个强类型列表。为什么要将其转换为弱类型的DataTable
然后再回到列表?????
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();
如果您希望能够在方法范围之外使用此列表,请定义一个包含不同属性的类型,并在select语句中使用此类型而不是匿名类型,如:
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();
答案 1 :(得分:2)
根据您显示的代码,您不需要数据表:
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();
答案 2 :(得分:2)
如果确实想要将数据表转换为1D列表,则可以这样做
foreach (DataRow row in dtTable.Rows)
{
foreach (DataColumn col in dtTable.Columns)
{
coa.Add(row[col]);
}
}
答案 3 :(得分:2)
正如您在linq查询中使用Select new它会找到对象。你能做的是
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 });
这是您的查询,您可以在查询中选择多个列。因此,您无法将数据转换为单个字符串列表。你可以做的是在一个字符串中连接所有列,然后将它们添加到字符串列表中。
要做到这一点修改您的查询,如'CK'说
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();
然后再做
List<string> name = new List<string>(data.ToList());