none
How do we get temperature value between the range using LINQ C# RRS feed

  • Question

  • I am passing the Turban variable value "2500". If this will check between the range of min and max column.
    if this value ("2500") within the range of min and max, then we should get the temperature value.

    Example data table given below.



    For this case, Temp value is ==> 7.5

    How do we form a code using LINQ C#.
    Friday, September 25, 2020 4:05 PM

Answers

  • class Program
        {
            sealed class Material
            {
                public string Name { get; set; }
                public int Min { get; set; }
                public int Max { get; set; }
                public double Temp { get; set; }
            }
            static void Main(string[] args)
            {
                var materials = new Material[]
                {
                    new Material{Name = "Turban", Min = 0, Max = 2000, Temp = 10},
                    new Material{Name = "Turban", Min = 2001, Max = 3000, Temp = 7.5},
                    new Material{Name = "Turban", Min = 3001, Max = 6000, Temp = 5},
                    new Material{Name = "Turban", Min = 6001, Max = 20000, Temp = 2.5},
                };
                int turbanValue = 2500;
                double matchingTemp = materials
                    .Where(m => turbanValue > m.Min && turbanValue < m.Max)
                    .Single()
                    .Temp;
            }
        }

    • Proposed as answer by CoolDadTxModerator Friday, September 25, 2020 6:08 PM
    • Marked as answer by Gani tpt Saturday, September 26, 2020 3:17 PM
    Friday, September 25, 2020 5:35 PM
  • The only adjustments I'd make to EckiS's code is that I'd use <= and >= otherwise you'll have boundary errors on 2000, 2001, 3000, etc. 

    The second thing I'd do is switch from Single to FirstOrDefault. This handles cases outside the 0-20000 range. Of course if that never occurs then it doesn't matter but I generally prefer FirstOrDefault over First/Single/etc.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by Gani tpt Saturday, September 26, 2020 3:17 PM
    Friday, September 25, 2020 6:10 PM
    Moderator
  • Hello,

    The following is what EckiS and CoolDataTx are pointing too essentially. The language extension is not needed although it makes code more readable and when placed in it's own class file or within a class project your main project references it's reusable.

    public partial class CodeSampleForm : Form
    {
    
        public CodeSampleForm()
        {
            InitializeComponent();
        }
    
        private void GetButton_Click(object sender, EventArgs e)
        {
            if (double.TryParse(TestValueTextBox.Text, out var value))
            {
                var materials = MockedDataTable();
                var result = materials
                    .AsEnumerable()
                    .FirstOrDefault(row =>
                        value.Between(row.Field<double>("Min"), row.Field<double>("Max")));
    
                MessageBox.Show(result == null ? 
                    $"{value} not found" : 
                    $"Temp: {result.Field<double>("Temp")}");
            }
            else
            {
                MessageBox.Show("Need a valid value");
            }
        }
    
        private static DataTable MockedDataTable()
        {
            DataTable dt = new DataTable();
    
            dt.Columns.Add(new DataColumn() {ColumnName = "MaterialName", DataType = typeof(string)});
            dt.Columns.Add(new DataColumn() {ColumnName = "Min", DataType = typeof(double)});
            dt.Columns.Add(new DataColumn() {ColumnName = "Max", DataType = typeof(double)});
            dt.Columns.Add(new DataColumn() {ColumnName = "Temp", DataType = typeof(double)});
    
            dt.Rows.Add("Turban", 0, 2000, 10);
            dt.Rows.Add("Turban", 2001, 3000, 7.5);
            dt.Rows.Add("Turban", 3001, 6000, 5);
            dt.Rows.Add("Turban", 6001, 20000, 2.5);
    
            return dt;
        }
    }
    public static class GenericExtensions
    {
        public static bool Between<T>(this IComparable<T> sender, T minimumValue, T maximumValue) =>
            sender.CompareTo(minimumValue) >= 0 && sender.CompareTo(maximumValue) <= 0;
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Gani tpt Saturday, September 26, 2020 3:17 PM
    Saturday, September 26, 2020 10:51 AM
    Moderator

All replies

  • class Program
        {
            sealed class Material
            {
                public string Name { get; set; }
                public int Min { get; set; }
                public int Max { get; set; }
                public double Temp { get; set; }
            }
            static void Main(string[] args)
            {
                var materials = new Material[]
                {
                    new Material{Name = "Turban", Min = 0, Max = 2000, Temp = 10},
                    new Material{Name = "Turban", Min = 2001, Max = 3000, Temp = 7.5},
                    new Material{Name = "Turban", Min = 3001, Max = 6000, Temp = 5},
                    new Material{Name = "Turban", Min = 6001, Max = 20000, Temp = 2.5},
                };
                int turbanValue = 2500;
                double matchingTemp = materials
                    .Where(m => turbanValue > m.Min && turbanValue < m.Max)
                    .Single()
                    .Temp;
            }
        }

    • Proposed as answer by CoolDadTxModerator Friday, September 25, 2020 6:08 PM
    • Marked as answer by Gani tpt Saturday, September 26, 2020 3:17 PM
    Friday, September 25, 2020 5:35 PM
  • The only adjustments I'd make to EckiS's code is that I'd use <= and >= otherwise you'll have boundary errors on 2000, 2001, 3000, etc. 

    The second thing I'd do is switch from Single to FirstOrDefault. This handles cases outside the 0-20000 range. Of course if that never occurs then it doesn't matter but I generally prefer FirstOrDefault over First/Single/etc.


    Michael Taylor http://www.michaeltaylorp3.net

    • Marked as answer by Gani tpt Saturday, September 26, 2020 3:17 PM
    Friday, September 25, 2020 6:10 PM
    Moderator
  • I am getting error below in the turbanvalue. Here materials is  a DataTable

    operator '>=' cannot be applied to operands of type 'double' and 'method group'

    I have modified as suggested by your idea <= and >=.

     int turbanValue = 2500;
                double matchingTemp = materials.AsEnumerable()
                    .Where(m => turbanValue >= m.Min && turbanValue <= m.Max)
                    .Single()
                    .Temp;

    Will it be okay...?



    • Edited by Gani tpt Saturday, September 26, 2020 4:37 AM materials is a DataTable
    Saturday, September 26, 2020 3:22 AM
  • Should be but you're using Single so if you get a value that is outside the ranges then it'll generate an error. You also technically can get an error if you happen to have any ranges that overlap. Single expects 1 and only 1 result. If you want to handle these boundary cases then use First (if you always expect a match) or FirstOrDefault (if you expect 0 or more matches).

    Michael Taylor http://www.michaeltaylorp3.net

    Saturday, September 26, 2020 5:34 AM
    Moderator
  • ok..thanks. i am using FirstOrDefault.

    I am getting error below in the turbanvalue. Here materials is  a DataTable

    operator '>=' cannot be applied to operands of type 'double' and 'method group'

    Saturday, September 26, 2020 5:49 AM
  • Hello,

    The following is what EckiS and CoolDataTx are pointing too essentially. The language extension is not needed although it makes code more readable and when placed in it's own class file or within a class project your main project references it's reusable.

    public partial class CodeSampleForm : Form
    {
    
        public CodeSampleForm()
        {
            InitializeComponent();
        }
    
        private void GetButton_Click(object sender, EventArgs e)
        {
            if (double.TryParse(TestValueTextBox.Text, out var value))
            {
                var materials = MockedDataTable();
                var result = materials
                    .AsEnumerable()
                    .FirstOrDefault(row =>
                        value.Between(row.Field<double>("Min"), row.Field<double>("Max")));
    
                MessageBox.Show(result == null ? 
                    $"{value} not found" : 
                    $"Temp: {result.Field<double>("Temp")}");
            }
            else
            {
                MessageBox.Show("Need a valid value");
            }
        }
    
        private static DataTable MockedDataTable()
        {
            DataTable dt = new DataTable();
    
            dt.Columns.Add(new DataColumn() {ColumnName = "MaterialName", DataType = typeof(string)});
            dt.Columns.Add(new DataColumn() {ColumnName = "Min", DataType = typeof(double)});
            dt.Columns.Add(new DataColumn() {ColumnName = "Max", DataType = typeof(double)});
            dt.Columns.Add(new DataColumn() {ColumnName = "Temp", DataType = typeof(double)});
    
            dt.Rows.Add("Turban", 0, 2000, 10);
            dt.Rows.Add("Turban", 2001, 3000, 7.5);
            dt.Rows.Add("Turban", 3001, 6000, 5);
            dt.Rows.Add("Turban", 6001, 20000, 2.5);
    
            return dt;
        }
    }
    public static class GenericExtensions
    {
        public static bool Between<T>(this IComparable<T> sender, T minimumValue, T maximumValue) =>
            sender.CompareTo(minimumValue) >= 0 && sender.CompareTo(maximumValue) <= 0;
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Gani tpt Saturday, September 26, 2020 3:17 PM
    Saturday, September 26, 2020 10:51 AM
    Moderator
  • Excellent..Thanks..

    Saturday, September 26, 2020 3:17 PM