c# find the max () of the table column in class model

sblb 1,166 Reputation points
2022-08-28T16:24:25.847+00:00

Hi,
I've a class model and I want to find the max of the Id column but I don't find the good way to write the max.

 public partial class Developer  
    {      
        [Key]  
        public int Id { get; set; }  
        [Required]  
        public DateTime DateCrea { get; set; }  
        public string EnvT {  
            get {  
                int t;  
                int  datecrea = DateCrea.Year;  
                  
                if (datecrea != 0)  
                {                      
                    t = Max(Id) + 1; // It's here that I want to put the max  
  
                    string ecr = t.ToString() + '/' + datecrea.ToString();  
  
                    return ecr;  
                }  
                return EnvT;  
            }   
            set { }  
        }    

Thanks in advance to your proposition

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,288 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 26,136 Reputation points
    2022-08-28T17:10:11.307+00:00

    Max() is an aggregate function used to find the largest value in a set (collection). Your example code is a single item not a collection. Please make a better effort to read the documentation and learn basic C#. Frankly, you code makes no logical sense...

    Aggregate Functions (Transact-SQL)
    Enumerable.Max Method (Example code is located at the bottom of the documentation)

    LINQ Max() example.

        class Program  
        {  
            static void Main(string[] args)  
            {  
                List<Developer> data = PopulateMockData();  
                int maxId = data.Max(d => d.Id);  
                Console.WriteLine($"maxId = {maxId}");  
      
                int nextId = maxId + 1;  
                Console.WriteLine($"nextId = {nextId}");  
            }  
      
            public static List<Developer> PopulateMockData()  
            {  
                List<Developer> data = new List<Developer>();  
                for (int i = 0; i < 10; i++)  
                {  
                    data.Add(new Developer() { Id = i, EnvT = $"Ent_{i}" });  
                }  
      
                return data;  
            }  
        }  
      
        public partial class Developer  
        {  
            public int Id { get; set; }  
            public string EnvT { get; set; }  
        }  
    

    Results

    maxId = 9  
    nextId = 10