none
How to get nearest rank values from the data table using LINQ C# RRS feed

  • Question

  • I have employee table and his marks.

    I just want to get nearest rank based on the parameter using LINQ C#.

    below is example:

    double GradeValue =  17.00;  ==> value 17.00 is not in the Grade List. But, it will go the nearest value to match in the grade

                                                         column. so the nearest value is 17.15 

                                                         For Grade 17.15 ==> Corresponding Rank is 0.375 (Final Rank Output is = 0.375)

    datatable

    I have written below LINQ Query. But, i want to find the nearest value.

    Rank = (dtEmp.AsEnumerable().Where(p => p.Field<double>("Grade") == GradeValue).Select(p => p.Field<double>("Rank"))).FirstOrDefault();

    Final Rank Output is = 0.375

    How to Modify the existing LINQ query or some other method..

    Note : we need to handle the null values in the column of "Grade". otherwise getting DBNull value error.

    Monday, March 9, 2020 7:10 AM

Answers

  • Try something like this:

    var f = dtEmp.AsEnumerable( )
    	.Where( r => !r.IsNull( "Grade" ) )
    	.Select( r => new { Rank = r.Field<double>( "Rank" ), Diff = Math.Abs( r.Field<double>( "Grade" ) - GradeValue ) } )
    	.OrderBy( d => d.Diff )
    	.FirstOrDefault( );
    
    double? rank = f?.Rank;
    

    • Marked as answer by Gani tpt Monday, March 9, 2020 10:06 AM
    Monday, March 9, 2020 9:17 AM

All replies

  • Try something like this:

    var f = dtEmp.AsEnumerable( )
    	.Where( r => !r.IsNull( "Grade" ) )
    	.Select( r => new { Rank = r.Field<double>( "Rank" ), Diff = Math.Abs( r.Field<double>( "Grade" ) - GradeValue ) } )
    	.OrderBy( d => d.Diff )
    	.FirstOrDefault( );
    
    double? rank = f?.Rank;
    

    • Marked as answer by Gani tpt Monday, March 9, 2020 10:06 AM
    Monday, March 9, 2020 9:17 AM
  • Thanks. it's working..
    Monday, March 9, 2020 10:06 AM