user2297683
user2297683

Reputation: 406

Maximum value in datatable column c#

I have a set of text files that I am reading into a datatable. I want to be able to read the frist column (Id) and find out the highest number. Each of the files goes from 0 to at least 21 sequentially. I tried suggestions from the following link: How to select min and max values of a column in a datatable?

Sadly, I could not any to work. The one suggestion that kind of worked is shown in the second last line, but it returns a value of 8 or 9. Any suggestions as to how to properly get the results I am looking for?

        string filePath = System.IO.Path.GetFullPath(curriculum);
        DataTable curriculmDataTable = new DataTable();

        curriculmDataTable.Columns.Add("Id");
        curriculmDataTable.Columns.Add("Course");
        curriculmDataTable.Columns.Add("Credit");

        // Read in a file line-by-line, and store it
        var txtFileLine = File.ReadAllLines(filePath).ToList();

        //Reads line splits data to colums at tab (ASCII value 9)
        txtFileLine.ForEach(line => curriculmDataTable.Rows.Add(line.Split((char)9)));


        //Suggestions from link
        int max = Convert.ToInt32(curriculmDataTable.Select("Id=max(Id)")[0][0]);   
        label1.Text = ""+ max;

Upvotes: 0

Views: 26260

Answers (2)

Praveen
Praveen

Reputation: 9

We can get max value from the column in a dataTable using this syntax

var maxValue = dataTblDetails.Compute("max(ColumnName)", string.Empty);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

The problem is that you have created string columns but you want to get the max-values according to their numeric value. The best way is to store the corrrect type in the first place. Then you could either use DataTable.Compute or Linq-To-DataSet:

create an int column:

 curriculmDataTable.Columns.Add("Id", typeof(int));

convert the strings to int and add them to the table:

foreach(string line in File.ReadLines(filePath))
{
    DataRow row = curriculmDataTable.Rows.Add();
    string[] fields = line.Split(new[]{(char)9});
    int id;
    if(fields.Length == 3 && int.TryParse(fields[0], out id)
    {
        row.SetField("Id", id);
        row.SetField("Course", fields[1]);
        row.SetField("Credit", fields[2]);
    }
}

Now you can use Linq:

int maxID = curriculmDataTable.AsEnumerable().Max(r => r.Field<int>("Id"));

DataTable.Compute (works also with earlier .NET versions):

int maxID = (int)curriculmDataTable.Compute("Max(Id)", "")

Upvotes: 4

Related Questions