Click here to Skip to main content
15,941,828 members
Articles / Programming Languages / C# 3.5

LINQ: Get all the values from a column in a DataTable in C#

Rate me:
Please Sign up or sign in to vote.
4.13/5 (7 votes)
13 Oct 2011CPOL 117.6K   4   5
LINQ: Get all the values from a column in a DataTable in C#
You can get the values from a named column in the DataTable using a single line of code in LINQ.


  1. Convert the DataTable object to Enumerable().
  2. Apply the select clause with the column name as field name.
  3. Cast it to a string array.
    string[] strSummCities = dtTemp1.AsEnumerable().Select(s => s.Field<string>("City")).ToArray<string>();


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Web Developer
India India
Software developer by profession, working for a service and product based organisation in India.

Career graph:
Software Programmer since 2002.
Web Developer in ASP.NET since 2004.

I love reading the blogs and articles of technology experts. I love codeproject and stackoverflow .

I love to share knowledge and help the programmers. I appreciate if some body corrects my code or my concepts which helps me learn.

Comments and Discussions

Questionany thoughts on distinct? Pin
Member 435337117-Nov-14 18:01
Member 435337117-Nov-14 18:01 
QuestionGetting "Specified cast is not valid" error Pin
Silas Pereira5-Dec-12 23:27
Silas Pereira5-Dec-12 23:27 

Thank you for your post, it will be very helpful, if I manage to put this working.
Smile | :)
I am using it to verify the unique values from a datatable column like this:

Validations.IsUnique<Int16>(data.Tables[0].AsEnumerable().Select(s => s.Field<Int16>(_rotationColumn)))

internal static bool IsUnique<T>(IEnumerable<T> values)
    var set = new HashSet<T>();

    foreach (T item in values)
        if (!set.Add(item))
            return false;
    return true;

But I am getting a "Specified cast is not valid" in the foreach loop. My database field is tinyint and I thought that casting the T as Int16 would solve the issue (I already tried with string, Int32 and int), but it is not working.

Could you please help me with that?

Silas Pereira

AnswerRe: Getting "Specified cast is not valid" error Pin
bbirajdar5-Dec-12 23:42
bbirajdar5-Dec-12 23:42 
GeneralReason for my vote of 1 Personally attacked because of provi... Pin
Kabwla.Phone20-Oct-11 2:03
Kabwla.Phone20-Oct-11 2:03 
QuestionNice Pin
Matt U.14-Oct-11 2:12
Matt U.14-Oct-11 2:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.