Click here to Skip to main content
Click here to Skip to main content

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

By , 13 Oct 2011
Rate this:
Please Sign up or sign in to vote.
You can get the values from a named column in the DataTable using a single line of code in LINQ.

Steps:
  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>();

License

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

About the Author

aspnet -i
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.
 
Interests:
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

 
QuestionGetting "Specified cast is not valid" error PinmemberSilas Pereira5-Dec-12 23:27 
Hi,
 
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?
 
Thanks.
Silas Pereira

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

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140415.2 | Last Updated 13 Oct 2011
Article Copyright 2011 by aspnet -i
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid