【问题标题】:Datatables, exceed, join数据表,超过,加入
【发布时间】:2012-04-13 14:05:06
【问题描述】:

我有一个名为sourceTable 的数据表,其中包含source_Idtitleprogramme_Id 列。第二个数据表是credits,列credit_Idprogramme_Id。所有列都是 Int 类型而不是列标题。

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

我想要实现的是从数据表credits 中使用列credit_Id 超过表sourceTable

我写了一个有效的代码,但是很慢,有没有更好的方法!,如果没有我正在寻找的项目,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;
}

【问题讨论】:

  • 两个数据表都有一些从 xml 文档中填充的内容
  • 我认为你不需要在 Convert.ToInt32(row["programme_Id"].ToString() 中转换成 ToString()
  • 它有点帮助(一分钟:),我有点麻烦,因为有很多行

标签: c# visual-studio-2010 linq


【解决方案1】:

它运行缓慢,因为您为源表中的每一行遍历 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"]);

【讨论】:

    【解决方案2】:

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

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

    干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-17
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 2021-11-16
      • 1970-01-01
      • 2019-02-18
      相关资源
      最近更新 更多