Search code examples
c#linqlinq-to-dataset

Select single column from dataset with LINQ


Just getting my head around all this LINQ stuff and it seems I'm stuck at the first hurdle.

I have a datatable as such:

OrderNo     LetterGroup Filepath
----------- ----------- --------------------------------------------------
0           0           Letters/SampleImage.jpg
0           0           Letters/UKPC7_0.jpg
0           0           Letters/UKPC8_0.jpg

What I need is to get all of the filepaths from the Filepath column into a String array. I thought LINQ would be perfect for this (am I right?), but can't seem to construct the correct query.

Can anyone provide some code samples that would point me in the right direction? I have searched around - but don't seem to be getting anywhere.


Solution

  • There are extension methods which make working with data sets much easier:

    using System.Data.Linq;
    
    var filePaths =
        from row in dataTable.AsEnumerable()
        select row.Field<string>("Filepath");
    
    var filePathsArray = filePaths.ToArray();
    

    You can also use the method syntax to put it in one statement:

    var filePaths = dataTable
        .AsEnumerable()
        .Select(row => row.Field<string>("Filepath"))
        .ToArray();