none
distinct and where clause togather in LINQ RRS feed

  • Question

  • Hi,

    I have a datatable whiche has 3 columns. col1, col2, col3

     

    I want to ave query which is like

    SELECT DISTINCT col1

    FROM DataTable

    WHERE col3 = 'value1'

     

    How can I implement same query in my datatable?

     

    Thanks

     

     

     

    Sunday, September 25, 2011 5:48 PM

Answers

  • Hi 1plus1is3;

    In the following query DataTable should be replaced by the instance name of the DataTable. Where you see Field<string> the type string should be replaced with the actual data type of the column in the DataTable. And where you see ("col1") and ("col3") replace col1 and col3 with the actual column names.

    var results = (from row in DataTable.AsEnumerable()
                   where row.Field<string>("col3") == "value1"
                   select row.Field<string>("col1")).Distinct();
    

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Marked as answer by anonymous12348 Tuesday, September 27, 2011 9:39 PM
    Monday, September 26, 2011 7:04 PM

All replies

  • Hi 1plus1is3:

    You would write a Linq query similiar to this:

     

    var results = (from DataRow the_row in MyDataTable.Rows
                                    where the_row["col3"] == "value1"
                                    select new {col1=the_row["col1"]}).Distinct()


     


    Tom Overton
    • Edited by Tom_Overton Sunday, September 25, 2011 10:06 PM
    Sunday, September 25, 2011 10:02 PM
  • Hi 1plus1is3;

    In the following query DataTable should be replaced by the instance name of the DataTable. Where you see Field<string> the type string should be replaced with the actual data type of the column in the DataTable. And where you see ("col1") and ("col3") replace col1 and col3 with the actual column names.

    var results = (from row in DataTable.AsEnumerable()
                   where row.Field<string>("col3") == "value1"
                   select row.Field<string>("col1")).Distinct();
    

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Marked as answer by anonymous12348 Tuesday, September 27, 2011 9:39 PM
    Monday, September 26, 2011 7:04 PM
  • This can also be easily acheived by using,

    datatable.Select("col3 = 'value1'").CopyToDataTable().DefaultView.ToTable(true);
    A DataTable will be returned..!
    With Best Regards, Boovendan M
    Tuesday, September 27, 2011 5:01 AM
  • thank you all. I got the answer
    Tuesday, September 27, 2011 9:39 PM
  •  

    Not a problem, glad I was able to help.

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Wednesday, September 28, 2011 1:13 PM