2017-04-08 53 views
0

我想轉換DataTable中使用C#這樣簡單的方法來轉換數據表使用C#

public void GetList() 
{ 

    ds = // here my dataset; 

    List<MasterList> result = new List<MasterList>(); 
    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) 
    { 
     foreach (DataRow dt in ds.Tables[0].Rows) 
     { 
      result.Add(new MasterList() 
      { 
       Name = Convert.ToString(dt["Name"]), 
       Address = Convert.ToString(dt["Address"]), 
       City = Convert.ToString(dt["City"]) 
      }); 

     } 
    } 
} 

這個代碼工作細到列表,列表,但我想知道簡單的方法來轉換數據表中列出,並這裏使用了foreach循環。

那麼這是什麼解決方案?

+0

1S谷歌http://stackoverflow.com/questions/1427484/convert-datatable-to-listt – TriV

+0

或http://stackoverflow.com/questions/208532 /怎麼辦,你變頻-A-數據表 - 到 - 一個泛型列表 – TriV

回答

1

使用LINQ,你可以做到以下幾點:

List<MasterList> result = ds.Tables[0].AsEnumerable().Select(m => new MasterList() 
{ 
    Name = Convert.ToString(dt["Name"]), 
    Address = Convert.ToString(dt["Address"]), 
    City = Convert.ToString(dt["City"]) 
}).ToList()