Link to home
Start Free TrialLog in
Avatar of ol muser
ol muserFlag for United States of America

asked on

Best way to select specific columns in a LINQ query


Being new to LINQ - In the code below how to select specific columns?

DataTable ResultView = LookUp(); //datatable has 3 columns

var query = (from lookup in ResultView.AsEnumerable()
            where lookup[2].ToString() == "cond" //this works
                select lookup[0], lookup[1] //??? Need only the first two columns
            );
Avatar of kaufmed
kaufmed
Flag of United States of America image

You would want to use the new keyword. You can pick an arbitrary name for each column:
var query = from lookup in ResultView.AsEnumerable()
            where lookup[2].ToString() == "cond" //this works
            select new
            {
                FirstColumn = lookup[0],
                SecondColumn = lookup[1] //??? Need only the first two columns
            };

// Use like this:
foreach (var item in query)
{
    Console.WriteLine(item.FirstColumn.ToString());
    Console.WriteLine(item.SecondColumn.ToString());
}

Open in new window

Avatar of ol muser

ASKER

Oh I forgot to mention, so here are the additional details and I am adding extra points.

I need to get the first two columns and as many rows as there are to a datatable. Is there a way to do that without using foreach in one single step...
Is there a way to do that without using foreach in one single step...
What is it you want to do with the data? Remember, declaring the query itself (lines 1 to 7 in my last post) don't actually execute the query; the query is executed, in my example, in the foreach line. You can return a list of these columns if you like (negating the use of a foreach):

var items = query.ToList();

Open in new window

I would like to store the resulting dataset in another datatable array

I would like to be able to return viewschemas[index] which is a Datatable.

I think I could do this now by(contd from above in pseudo code) :

Datatable x = new Datatable();
foreach(var item in query)
{
   x.addrow(query.datarow);
}

viewSchema[indx] = x;
return viewSchema[index];

It may look twisted but I am trying to use existing code as part of maintenance.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
P.S.

The following using statements are required for the code at that link:

using System;
using System.Data;
using System.Collections.Generic;
using System.Reflection;

Open in new window

@Kaufmed, did you try to compile the code?

Or is it meant to be pseudocode?
did you try to compile the code?
Did you add the code that I referred to in the link? The code I posted is not the entire solution--you need the code from the link as well. Just #1 and #2, though.