none
how to select distinct data from a datarow in c# RRS feed

  • Question

  • Hi,

    I have a datatable (dt), from which I have selected some rows and stored them in datarow[] (dr). Now I am going to query on the datarow for distinct rows, but do not know how to do it?

    thanks

    Arvin

    datatable dt = new datatable();

    dt has three columns of name, value, and year.

    here are data in dt:

    ('jack',32,1999)

    ('jack',45,1954)

    ('jack',45,1943)

    ('jack',65,1979)

    ('ed',32,1669)

    ('ed',32,1889)


    datarow[] dr = dt.select("name = 'jack' ")

    I want to find:

    1-those distinct rows from dr, based on distinct value: I want to get 32,45,65

    2-then query through dr using distinct value of 32,45,65

    Wednesday, May 9, 2012 10:09 PM

Answers

  • 1. To get the distinct values the easiest way is to use LINQ query:

    var query = dr.Select(x => x.Field<int>("Value")).Distinct();
    
    foreach (var value in query)
    {
        Console.WriteLine(value);
    }

    2. What do you mean by query through dr with values from first query? Something like following, which actually gives you the result of first select or do you want just one "Jack, 45" in the results.

    var query2 = dr.Where(x => query.Contains(x.Field<int>("Value")));
    
    foreach (var value in query2)
    {
       Console.WriteLine(value["Name"] + ", " + value["Value"] + ", " + value["Year"]);
    }

    Thursday, May 10, 2012 5:16 AM

All replies