none
Select distinct rows from Datatable using Linq and iterate through them RRS feed

  • Question

  • Hi,
    How can I use Linq to select distinct rows from a Datatable and iterate through the filtered rows. Please advice.
    regards
    Sreejith
    Friday, May 15, 2009 2:20 PM

Answers

  •  var distinctRows = (from DataRow dRow in dTable.Rows
                                    select new {col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();

                foreach (var row in distinctRows)
                {
                    var value1=row.col1.ToString();
                    var value2=row.col2.ToString(); 
                       
                }

    Monday, July 13, 2009 5:00 PM
  • Also see

    Select DISTINCT on DataTable

    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Saturday, May 16, 2009 4:28 PM
  • Also use the System.Data.DataRowComparer.Default comparer object so the element equality will be properly determined.
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Monday, July 13, 2009 5:08 PM

All replies

  • From MSDN. LINQ supports a distinct items. The same method would work on querying a Sql table:

    List<int> numbers = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

    IEnumerable<int> distinctNumbers = numbers.Distinct();

    foreach (int number in distinctNumbers)
        Console.WriteLine(number);


    Just query a datatable into a var object and step through it with a foreach.
    Friday, May 15, 2009 2:34 PM
  • Also see

    Select DISTINCT on DataTable

    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Saturday, May 16, 2009 4:28 PM
  •  var distinctRows = (from DataRow dRow in dTable.Rows
                                    select new {col1=dRow["dataColumn1"],col2=dRow["dataColumn2"]}).Distinct();

                foreach (var row in distinctRows)
                {
                    var value1=row.col1.ToString();
                    var value2=row.col2.ToString(); 
                       
                }

    Monday, July 13, 2009 5:00 PM
  • Also use the System.Data.DataRowComparer.Default comparer object so the element equality will be properly determined.
    John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com
    Monday, July 13, 2009 5:08 PM
  • thanks yaar. It works for me.
    Regards, Ramesh R
    Thursday, June 23, 2011 3:06 PM
  • Thanks its worked

     



    MCTS,MCPD Sharepoint 2010. My Blog- http://www.sharepoint-journey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Vote as Helpful

    Sunday, September 11, 2011 1:14 PM