Aggregate methods in Linq Query - Linq

Jul 13, 2019 BY xtreme
1. ANY Method

Returns a Boolean value. Returns True even if a single element satisfies the condition. Return False if 
none of the elements satisfies the condition..
	
Linq to sql
public bool CheckStudents()
{
    bool check = false;
    using (DbContextModel _db = new DbContextModel())
    {
	    check = _db.student.Where(x => x.is_active && !x.is_deleted).Any();
	    return check;
    }
}

Linq to Array

string[] students= { };
bool IsEmpty = students.AsQueryable().Any(); 


2. ALL Method Returns a Boolean value. Returns true if all the elements satisfy the condition otherwise it returns false.

	
Linq to sql
public bool CheckStudents()
{
    bool check = false;
    using (DbContextModel _db = new DbContextModel())
    {
	    check = _db.student.Where(x => x.is_active && !x.is_deleted && x.StartsWith("D")).All();
	    return check;
    }
}

Linq to Array

string[] students= { "jhon", "Richa", "Deepak", "Dipesh", "Mohan" };
bool IsStartWith_D = students.AsQueryable().All(s=> s.StartsWith("D")); 


Overload of All

Get All the students with Name Start with Character D. 
public List GetStudents()
{    
    using (DbContextModel _db = new DbContextModel())
    {
	var result = _db.student.Where(x => x.is_active && !x.is_deleted).AsQueryable()
        .All(x => x.StartsWith("D")).Select(x => new StudentModel
	{
		id = x.id,
		name = x.name,		
		status = x.is_active ? "Active" : "Inactive"
	}).ToList();
    }
}



3. SUM Method

Calculate total(sum) value of the collection.
	
Linq to sql
public Student GetStudentDetails(int id)
{    
    using (DbContextModel _db = new DbContextModel())
    {
	var result = _db.student.Where(x => x.is_active && !x.is_deleted).Select(x => new StudentModel
	{
	    id = x.id,
	    deposit = _db.payments.Where(p => p.id== id).Sum(p => p.amount),
	}).FirstOrDefault();

	return result;
    }
} 






Related