Share via


LINQ IEnumerable Select

Question

Thursday, July 7, 2016 4:36 PM

I've been using following LINQ for querying records from IEnumerable(Datarow). Instead of hardcoding field names in Linq, I want to pass string[] as input parameter and field names needs to be retrieved from string[]. Please assist me on this.

List<string[]> IDcolls = drResults.Select(q => new[]   
                                {   
                                     q["empid"].ToString(),                                      
                                     q["empname"].ToString()   
                                })  
                                .Skip(mBatch * batchSize)  
                                .Take(batchSize)  
                                .ToList();  
string[] IDs = (from q in drResults  
                            select q["empid"].ToString())  
                            .Skip(i * batchSize)  
                            .Take(batchSize)  
                            .ToArray();

All replies (2)

Thursday, July 7, 2016 5:01 PM ✅Answered | 1 vote

For the first case, try ‘drResults.Select( q => names.Select( n => q[n].ToString())…’, where names is ‘string[] names = { "empid","empname" }’.

For the second case, try ‘(from q in drResults select (from n in names select q[n].ToString()).ToArray())…’, but the results should be declared as ‘string[][] IDs’.


Thursday, July 7, 2016 6:44 PM

Please refer to the following sample code:

            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("empid"));
            dt.Columns.Add(new DataColumn("empname"));
            dt.Rows.Add("1", "a");
            dt.Rows.Add("2", "a");
            var drResults = dt.AsEnumerable();

            string[] theNames = new string[2] { "empid", "empname" };
            Func<DataRow, string[]> selector = row => theNames.Select(x => row[x].ToString()).ToArray();
            List<string[]> IDcolls = drResults.Select(selector)
                                //.Skip(mBatch * batchSize)
                                //.Take(batchSize)
                                .ToList();

            string columnName = "empid";
            string[] IDs = (from q in drResults
                            select q[columnName].ToString())
                            //.Skip(i * batchSize)
                            //.Take(batchSize)
                            .ToArray();

Hope that helps.

Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.