简体   繁体   中英

Fastest way to insert data from a column in all DataTables in a DataSet to a List

Basically, I need to get the email column from each table in the DataSet (there could be 0 tables in there, or there could be 100) and slap them together into a big List for processing later.

I was about to write the 2x nested loop to do it, but is there an easier way to type this?

My first attempt at loops didn't work so well, since DataTables don't define GetEnumerator :

foreach(DataTable item in emailTables.Tables)
{
    foreach(var email in item)
    {
     // This doesn't work
    }
}

Like LB said, it's opinion based, but LINQ would be my first choice. A bit less readability but less typing overall and definitely less nesting.

var listEmail = (from DataTable table in emailTables.Tables 
                 from DataRow row in table.Rows 
                 select row["yourColumnNameHere"].ToString()).ToList();

If any of the tables do not (or may not) have an email column, then you will have to do some more validation.

I chose to use a separate answer to extend the question posed in a comment after my initial answer was accepted.

The question was:

I'm considering making this into an extension method, would it be possible to extend this code to obtain multiple items, like Email, Name and Address? Maybe into something other than List<>?

The answer:

Create Anonymous types in a the select statement and assign different values from the columns to those types:

var selectedItems = from DataTable table in emailTables.Tables
            from DataRow row in table.Rows
            select
                new
                {
                    EMail = row["email"].ToString(),
                    Address = row["address"].ToString(),
                    Name = row["name"].ToString()
                };

Then loop through the results in selectedItems and do whatever you would like to the fields. Not sure what type you want to store the results in, but this should give you a pretty good idea.

        foreach (var item in selectedItems)
        {
            //Do whatever you want by accessing the fields EMail, Address, and Name using dot notation like
            var myVar = item.EMail;
            var myVar2 = item.Address;
            //Etc... Not sure what the end result you need is going to be, but you should have a good starting point now.
        }

OR you could just return the selectedItems collection. It's type is IEnumerable<T> .

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