Calculation in Linq Query- Linq

Jul 11, 2019 BY xtreme
Compute Sum via Linq
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,
			total = x.payments.Where(p => p.id == x.id && p.amount != null).Sum(p => p.amount.Value).ToString("N2"),
		}).FirstOrDefault();

		return result;
	}
}
Get Comma Separated string of value via Linq
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,
			subjects = String.Join(",", _db.subjects.Where(y => y.id == x.id).Select(y => y.id).ToArray()),
		}).FirstOrDefault();

		return result;
	}
}

Use variable in Linq for calculated value
public Student GetStudentDetails(int id)
{
	using (DbContextModel _db = new DbContextModel())
	{
		var result = (	from s in student
		let class = s.classes == null ? "" : s.classes.classno
	     select new StudentModel
	     {
		     id = x.id,
		     ClassNo = class,
	     }).ToList();

		return result;
	}
}




Related