C# .NET - Max ID in LINQ - Asked By mostafa hamdy on 06-Mar-12 12:15 PM

Hello All
I have some List<Employees> and every employee has ID,Name , Address and Title
and I want to use the Linq to get the Employee with the MAX , please if any body can  help me please send me or tell me about some URL may help me in doing that
Regards
Mostafa
Devil Scorpio replied to mostafa hamdy on 06-Mar-12 12:59 PM
Hi,

You can get the max ID in LINQ by following query

var query = (from q in db.Status select q.ConfigurationItemId).Max();

OR

int latestStatusCode = db.Status.Where(elem => elem.ConfigurationItemId == 21).OrderByDescending(e => e.Id).FirstOrDefault().StatusCode;

For more info, refer
http://forums.asp.net/t/1427993.aspx
[)ia6l0 iii replied to mostafa hamdy on 06-Mar-12 10:18 PM
I am not sure about the other replies above. There is a simpler way. See the following example.

If this is your employee class,
public class Employee
{
        public int ID { get; set; }
        public string Name { get; set; }
}

And this is how the list is,
List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { ID = 10, Name = "John Hook" });
employees.Add(new Employee() { ID = 12, Name = "Chritopher Null" });
employees.Add(new Employee() { ID = 11, Name = "James Walter Jr." });

 
Then, the following statement would give you the Max ID.
int maxValue = employees.Max(e => e.ID);

Thank you.
Web Star replied to mostafa hamdy on 06-Mar-12 11:50 PM
Simply try this

int maxId = (from c in Employees  select c.Id).Max();

hope this helps you
Danasegarane Arunachalam replied to mostafa hamdy on 07-Mar-12 12:14 AM
The code posted by[)ia6l0 will work only if there are some items in the list.

If there are no items in the list then you will get exception

Take this example

List<Employee> employees = new List<Employee>();
int maxValue = employees.Max(e => e.ID);

The above will return a exception as  "Sequence contains no Elements" , As there are no elements in the array the system is not able to find the max value in the collection.

To avoid this error use the DefaultIfEmpty Method id addition

See the below example


        List<Employee> employees = new List<Employee>();
        
        int maxValue = employees.Select(emp => emp.ID).DefaultIfEmpty().Max();
        

        employees.Add(new Employee() { ID = 10, Name = "John Hook" });
        employees.Add(new Employee() { ID = 12, Name = "Chritopher Null" });
        employees.Add(new Employee() { ID = 11, Name = "James Walter Jr." });

        maxValue = employees.Select(emp => emp.ID).DefaultIfEmpty().Max();


This works even if the collection contains no elements

Reena Jain replied to mostafa hamdy on 07-Mar-12 01:30 AM
Hi,

You can try with the following LINQ query , which shows you how to use MAX.


var q = from s in db.employee
  select new {s.Max(s => s.uid) }

or

var q= (from s in context.employee

select (o.ID)).Max();

or provide your query to solve the problem