我有一个工具和工人的汇总表。因此,我无法处理的任务是如何在汇总表中获得不涉及的最后工具的计数。我想应该是这样的
var res = context.ToolsSummaryTable.Include(t => t.Tool).Include(t => t.Worker)
where(t.Tool.Name.Count() > t.Tool.Quantity);
请帮忙!
汇总表数据
WorkerID | ToolID | 1 | 2 | 2
---|---|
3 | |
3 | 2 |
2 |
需要左外连接。
左外连接是:"from tuUsedNone in g.b defaultifempty ()"参见下面的代码
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Context context = new Context()
{
Sumary = new List<Summary>()
{
new Summary() {WorkerId = 1, ToolId = 2 },
new Summary() {WorkerId = 2, ToolId = 3 },
new Summary() {WorkerId = 3, ToolId = 2 },
new Summary() {WorkerId = 1, ToolId = 2 }
},
Tools = new List<Tools>()
{
new Tools() { ToolId = 1, Name = "Screwdriver", Quantity = 2},
new Tools() { ToolId = 2, Name = "Hummer", Quantity = 3},
new Tools() { ToolId = 3, Name = "Wrench 17", Quantity = 1},
new Tools() { ToolId = 4, Name = "Pipe Wrench", Quantity = 2}
},
Workers = new List<Workers>()
{
new Workers() { WorkerId = 1, FirstName = "Andrew", LastName = "Greekman"},
new Workers() { WorkerId = 2, FirstName = "Gordon", LastName = "Wingman"},
new Workers() { WorkerId = 3, FirstName = "Sam", LastName = "Peacekeeper"},
new Workers() { WorkerId = 4, FirstName = "Antony", LastName = "Scout"}
}
};
var toolsUsed = context.Sumary.GroupBy(x => x.ToolId)
.Select(x => new { toolId = x.Key, quantityUsed = x.Count() });
var toolsRemaining = (from t in context.Tools
join tu in toolsUsed on t.ToolId equals tu.toolId into g
from tuUsedNone in g.DefaultIfEmpty()
select (new { Name = t.Name, toolsRemaining = (tuUsedNone == null) ? t.Quantity : t.Quantity - tuUsedNone.quantityUsed }))
.ToList();
}
}
public class Context
{
public List<Summary> Sumary { get; set; }
public List<Tools> Tools { get; set; }
public List<Workers> Workers { get; set; }
}
public class Summary
{
public int WorkerId { get; set; }
public int ToolId { get; set; }
}
public class Tools
{
public int ToolId { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
}
public class Workers
{
public int WorkerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}