[Fork] [Fork] [Fork] [Fork] SO Question Group By With Having Clause LINQ 27730743

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
	public static void Main()
	{
		List<Contract> Contracts = new List<Contract>()
		{
		new Contract
		{
		ID = 1, LearningPackageID = 2
		}

		, new Contract
		{
		ID = 2, LearningPackageID = 4
		}

		, new Contract
		{
		ID = 3, LearningPackageID = 6
		}

		, new Contract
		{
		ID = 4, LearningPackageID = 8
		}
		}

		;
		List<DepositHistory> DepositHistories = new List<DepositHistory>()
		{
		new DepositHistory
		{
		CotractID = 1, Value = 100
		}

		, new DepositHistory
		{
		CotractID = 2, Value = 50
		}

		, new DepositHistory
		{
		CotractID = 3, Value = 200
		}
		}

		;
		List<LearningPackage> LearningPackages = new List<LearningPackage>()
		{
		new LearningPackage
		{
		ID = 2, COntractValue = 100
		}

		, new LearningPackage
		{
		ID = 4, COntractValue = 200
		}

		, new LearningPackage
		{
		ID = 6, COntractValue = 300
		}

		, new LearningPackage
		{
		ID = 8, COntractValue = 400
		}
		}

		;
		var Result = Contracts.GroupJoin(DepositHistories, a => a.ID, b => b.CotractID, (a, b) => new
		{
		a = a, b = b
		}

		).Join(LearningPackages, a => a.a.LearningPackageID, b => b.ID, (a, b) => new
		{
		a = a, b = b
		}

		).GroupBy(e => new
		{
		e.a.a.ID, e.b.COntractValue
		}

		, (k, g) => new
		{
		ID = k.ID, ContractValue = k.COntractValue, Value = g.Sum(x => x == null ? 0 : x.a.b.Sum(d => d.Value))}

		).Where(x => x.Value < x.ContractValue || x.Value == 0).ToList();
		foreach (var item in Result)
		{
			Console.WriteLine(item);
		}
	}
}

public class Contract
{
	public int ID
	{
		get;
		set;
	}

	public int LearningPackageID
	{
		get;
		set;
	}
}

public class DepositHistory
{
	public int CotractID
	{
		get;
		set;
	}

	public int Value
	{
		get;
		set;
	}
}

public class LearningPackage
{
	public int ID
	{
		get;
		set;
	}

	public int COntractValue
	{
		get;
		set;
	}
}
;