ここ

2013-06-14 3 views
36

リストへDataSetを変換し、私のC#コードは、それがここ

を一覧表示するデータセットを変換するために、そこに任意の直接法や短いメソッドまたは1行のコードをdataset.Isからリストを作成するために、ループを使用し

Employee objEmp = new Employee(); 
List<Employee> empList = new List<Employee>(); 
foreach (DataRow dr in ds.Tables[0].Rows) 
{ 
    empList.Add(new Employee { Name = Convert.ToString(dr["Name"]), Age = Convert.ToInt32(dr["Age"]) }); 
} 

です

+0

なぜ* One Line *にする必要がありますか?読みやすいように、現在のマルチライン形式ですか? –

+3

@JensKlosterは1行で書くことができるかどうかを知る上で害です:) – iJade

答えて

63

このような何か試してみてください:

var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Employee{Name = dataRow.Field<string>("Name")}).ToList(); 
+1

これは私が試したものです--- var empList = ds.Tables [0] .AsEnumerable()。Select(dataRow => new Employee {Name = dataRow.Field ( "名前")、Age = dataRow.Field ( "年齢")})。ToList(); 「指定されたキャストは無効です」と表示されます – iJade

+0

年齢はdbnullですか? – Carra

+1

いいえ..... – iJade

-1

は、任意のリストタイプで実行する上で試してみてください。

public DataTable ListToDataTable<T>(IList<T> data) 
    { 
     PropertyDescriptorCollection props = 
      TypeDescriptor.GetProperties(typeof(T)); 
     DataTable table = new DataTable(); 
     for (int i = 0; i < props.Count; i++) 
     { 
      PropertyDescriptor prop = props[i]; 
      table.Columns.Add(prop.Name, prop.PropertyType); 
     } 
     object[] values = new object[props.Count]; 
     foreach (T item in data) 
     { 
      for (int i = 0; i < values.Length; i++) 
      { 
       values[i] = props[i].GetValue(item); 
      } 
      table.Rows.Add(values); 
     } 
     return table; 
    } 
15
var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee { 
    Name = r.Field<string>("Name"), 
    Age = r.Field<int>("Age") 
}); 
var list = myData.ToList(); // For if you really need a List and not IEnumerable 
19

ここでリストをオブジェクトへのDataTableを変換する拡張メソッドです:

public static class Extensions 
    { 
     public static List<T> ToList<T>(this DataTable table) where T : new() 
     { 
      IList<PropertyInfo> properties = typeof(T).GetProperties().ToList(); 
      List<T> result = new List<T>(); 

      foreach (var row in table.Rows) 
      { 
       var item = CreateItemFromRow<T>((DataRow)row, properties); 
       result.Add(item); 
      } 

      return result; 
     } 

     private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new() 
     { 
      T item = new T(); 
      foreach (var property in properties) 
      { 
       if (property.PropertyType == typeof(System.DayOfWeek)) 
       { 
        DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString()); 
        property.SetValue(item,day,null); 
       } 
       else 
       { 
        if(row[property.Name] == DBNull.Value) 
         property.SetValue(item, null, null); 
        else 
         property.SetValue(item, row[property.Name], null); 
       } 
      } 
      return item; 
     } 
    } 

用法:itay.b CODE @

List<Employee> lst = ds.Tables[0].ToList<Employee>(); 

は、次のように説明し 私たちは、最初に、すべての読み取りリフレクションを使用してクラスTからのプロパティ名
次に、データテーブルのすべての行を繰り返し、Tの新しいオブジェクトを作成します。
次に、リフレクションを使用して新しく作成されたオブジェクトのプロパティを設定します。

プロパティ値は、行の一致する列セルから選択されます。

PS:クラスのプロパティ名とテーブルの列名は、ニーズごとにコードを変更....これを試してみてください

+0

このコードを説明してください。 –

+0

更新された回答を確認してください –

+0

この素晴らしい、素晴らしい答えとジェネリックの良い例が大好きです。 – Simon

2

同じでなければなりません。

 List<Employee> target = dt.AsEnumerable() 
     .Select(row => new Employee 
     { 
     Name = row.Field<string?>(0).GetValueOrDefault(), 
     Age= row.Field<int>(1) 
     }).ToList(); 
+2

ほんの少しのコメントですが、文字列はすでにnull可能です。文字列を使用するのに使用できませんか? – Carra

+0

ToList()メソッドが見つかりません。 – Blossom

1

ファイルに、ストアドプロシージャのコマンドは、スキーマを取得します

DbDataAdapter adapter = DbProviderFactories.GetFactory(cmd.Connection).CreateDataAdapter(); 
adapter.SelectCommand = cmd; 
DataSet ds = new DataSet(); 
adapter.Fill(ds); 

言う、からのデータと一緒に保存

string s = ds.GetXmlSchema(); 

をデータセットを塗りつぶしは言う:datasetSchema.xsdを。スキーマのためのC#クラスを生成します。(VSコマンドプロンプト)

xsd datasetSchema.xsd /c 

さて、あなたはデシリアライズできるクラスにDataSetにデータを変換する必要がある場合(生成されたルートクラスに与えられたデフォルトの名前がNewDataSetです) :

public static T Create<T>(string xml) 
{ 
    XmlSerializer serializer = new XmlSerializer(typeof(T)); 
    using (StringReader reader = new StringReader(xml)) 
    { 
     T t = (T)serializer.Deserialize(reader); 

     reader.Close(); 
     return t; 
    } 
} 

var xml = ds.GetXml(); 
var dataSetObjects = Create<NewDataSet>(xml); 
+0

+1です。これは[自分のXMLシリアル化/デシリアライズの質問](http://stackoverflow.com/questions/28652889/serializing-objects-into-xml-repository)の答えに私を近づけます。 –

1
   DataSet ds = new DataSet(); 
       ds = obj.getXmlData();// get the multiple table in dataset. 

       Employee objEmp = new Employee();// create the object of class Employee 
       List<Employee > empList = new List<Employee >(); 
       int table = Convert.ToInt32(ds.Tables.Count);// count the number of table in dataset 
       for (int i = 1; i < table; i++)// set the table value in list one by one 
       { 
        foreach (DataRow dr in ds.Tables[i].Rows) 
        { 
         empList.Add(new Employee { Title1 = Convert.ToString(dr["Title"]), Hosting1 = Convert.ToString(dr["Hosting"]), Startdate1 = Convert.ToString(dr["Startdate"]), ExpDate1 = Convert.ToString(dr["ExpDate"]) }); 
        } 
       } 
       dataGridView1.DataSource = empList; 

enter image description here

0

使用以下のコード:

using Newtonsoft.Json; 
string JSONString = string.Empty; 
JSONString = JsonConvert.SerializeObject(ds.Tables[0]); 
2

「ヘルパー」という名前の新しいクラスを追加し、「パブリック静的」

public static class Helper 
{ 
    public static List<T> DataTableToList<T>(this DataTable table) where T : class, new() 
    { 
     try 
     { 
      List<T> list = new List<T>(); 

      foreach (var row in table.AsEnumerable()) 
      { 
       T obj = new T(); 

       foreach (var prop in obj.GetType().GetProperties()) 
       { 
        try 
        { 
         PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name); 
         propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); 
        } 
        catch 
        { 
         continue; 
        } 
       } 

       list.Add(obj); 
      } 

      return list; 
     } 
     catch 
     { 
      return null; 
     } 
    } 
} 

にクラスのプロパティを変更し、

DataTable dtt = dsCallList.Tables[0]; 
List<CallAssignment> lstCallAssignement = dtt.DataTableToList<CallAssignment>(); 
-1
List<GSTEntity.gst_jobwork_to_mfgmaster> ListToGetJwToMfData = new List<GSTEntity.gst_jobwork_to_mfgmaster>(); 
      DataSet getJwtMF = new DataSet(); 
      getJwtMF = objgst_jobwork_to_mfgmaster_BLL.GetDataJobWorkToMfg(AssesseeId, PremiseId, Fyear, MonthId, out webex); 
      if(getJwtMF.Tables["gst_jobwork_to_mfgmaster"] != null) 
      { 

       ListToGetJwToMfData = (from master in getJwtMF.Tables["gst_jobwork_to_mfgmaster"].AsEnumerable() select new GSTEntity.gst_jobwork_to_mfgmaster { Partygstin = master.Field<string>("Partygstin"), Partystate = 
             master.Field<string>("Partystate"), NatureOfTransaction = master.Field<string>("NatureOfTransaction"), ChallanNo = master.Field<string>("ChallanNo"), ChallanDate=master.Field<int>("ChallanDate"), OtherJW_ChallanNo=master.Field<string>("OtherJW_ChallanNo"), OtherJW_ChallanDate = master.Field<int>("OtherJW_ChallanDate"), 
        OtherJW_GSTIN=master.Field<string>("OtherJW_GSTIN"), 
        OtherJW_State = master.Field<string>("OtherJW_State"), 
        InvoiceNo = master.Field<string>("InvoiceNo"), 
        InvoiceDate=master.Field<int>("InvoiceDate"), 
        Description =master.Field<string>("Description"), 
        UQC= master.Field<string>("UQC"), 
        qty=master.Field<decimal>("qty"), 
        TaxValue=master.Field<decimal>("TaxValue"), 
        Id=master.Field<int>("Id")       

       }).ToList(); 
以下などの背後にあるコードの中で、このクラスにアクセス
+0

上記のソースコードに説明を加えてください。 – Dominique