简体   繁体   中英

How to convert List<DataRow> to List<T> in C#?

How can I convert DataTable.Rows collection to List<Category> ?

I want to set the value of list of values of Data Row in to the List of values of C# object as I mentioned in the below code. kindly advice.

UserData objUserData = null;
DataTable dtUserData = DataAccess.getUserDataTable();  
if(dtUserData.Rows.Count>0)
{
    foreach(DataRow dr in dtUserData.Rows)
    {
      objUSerData = new UserData();
      List<objUSerData.Category> = Convert.ToString(List<dr["category"]>);
    } 
}

Here is the Category class:

[DataContract]
public class category { get; set; }
{
  public string category_id {get; set;}
  public string category_name {get; set;}
}

Just guessing:

You probably want to create UserData from your rows:

foreach(DataRow dr in dtUserData.Rows)
{
   var userData = new UserData();
   // create an array with a single element
   userData.Categories = new [] 
   {
     new Category
     {
       category_id = ??,
       category_name = Convert.ToString(dr["category"])
     }
   };
   // not sure about this:
   userData.UserDetails = new [] 
   {
     new UserDetails
     {
       Whatever = Convert.ToString(dr["userdetails"]),
     }
   };
}

I actually don't know what kind of type dr["userdetails"] is.

Probably you need to map the rows to entities. These entities are probably found in another database. The category is probably already found there, and if not, it probably needs to be created. If so, everything is much more complicated.

The user data is most probably a more complicated record and I don't have a clue whats behind the field in the row.

Because there is no more information in the question, I can only guess.

You can create instances of category class using linq or a loop:

DataTable dtUserData = DataAccess.getUserDataTable();
var list = dtUserData.Rows.Cast<DataRow>()
                     .Select(row => new category()
                     {
                         category_id = row.Filed<string>("category_id"),
                         category_name = row.Filed<string>("category_name"),
                     }).ToList();

It's equivalent to:

var list = new List<category>();
foreach(DataRow row in dtUserData.Rows)
{
    list.Add(new category()
        {
            category_id = row.Filed<string>("category_id"),
            category_name = row.Filed<string>("category_name"),
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM