2

我有DatatablesourceTable用 columnssource_Id和. 第二个数据表带有列, 。所有列都是 Int 类型而不是列标题。titleprogramme_Idcreditscredit_Idprogramme_Id

programme_Id数据表中的列credits是外键 FROM 数据表sourceTable

我想要实现的是 Exceed table sourceTablewith Column credit_Idfrom datatable credits

我写了一个有效的代码,但是很慢,有没有更好的方法!,如果没有我正在寻找的项目,FirstOrDefault 将放置 0,对于这种情况,也许会更好地返回 null 值而不是 0

sourceTable.columns.Add("credits_Id");
var rowColl = credits.AsEnumerable();
foreach (DataRow row in sourceTable.Rows)
{
    var credits_Id =
        (from r in rowColl
         where r.Field<int>("programme_Id") == Convert.ToInt32(row["programme_Id"].ToString())
         select r.Field<int>("credits_Id")).FirstOrDefault<int>();

    row["credits_Id"] = credits_Id;
}
4

2 回答 2

0

以防谷歌把某人带到这里:这是我现在提出的问题的解决方案:)

var q = from c in sourceTable.AsEnumerable()
                    join o in credits.AsEnumerable() on c.Field<int>("programme_Id") equals o.Field<int>("programme_Id") into outer
                    from o in outer.DefaultIfEmpty()
                    select new
                    {

                        title=c.Field<string>("title"),

                        credits_Id = (o==null)?-1:o.Field<int>("credits_Id")
                    };
            var qToList = q.ToList();

现在我们可以将此列表转换为数据表:

public static DataTable ListToDataTable<T>(List<T> list)
    {
        DataTable dtToConvert = new DataTable();
        try
        {

        foreach (PropertyInfo info in typeof(T).GetProperties())
        {
            dtToConvert.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }
        foreach (T t in list)
        {
            DataRow row = dtToConvert.NewRow();
            foreach (PropertyInfo info in typeof(T).GetProperties())
            {
                row[info.Name] = info.GetValue(t, null);
            }
            dtToConvert.Rows.Add(row);
        }

        } catch(Exception ex)
            {


            }
        return dtToConvert;
    }

干杯!

于 2012-04-16T21:09:54.230 回答
0

它运行缓慢,因为您为源表中的每一行遍历 credits 表中的所有行。您可以使用以下 linq 查询来连接两个表。

(from sourceRow in sourceTable.Rows.OfType<DataRow>()
join creditRow in credits.Rows.OfType<DataRow>()
   on sourceRow.Field<int>("programme_Id") equals creditRow.Field<int>("programme_Id")
select new {sourceRow, creditRow})
   .ForEach(o => o.sourceRow["credits_id"] = o.creditRow["sourceRow"]);
于 2012-04-13T14:28:08.790 回答