[英]LINQ C# - Select with group by and count to compare two entities based on count
我有两个实体,它们具有相同的ID列,如下表“ A”所示:
| CategoryID | ProductID |
|------------|-----------|
| 1 | 4 |
| 1 | 5 |
| 2 | 7 |
在LINQ语句中,我只想从表A中选择对象,其中按类别ID(在两个表上)分组的ProductID的数量在表B中较少。
因此,在上表中,类别ID 1的按计数分组为2。 如果表B中存在相同的CategoryID,并且仅具有一个基于分组计数的ProductID,则检索该对象。
我希望您能举例说明如何完成此操作。 也许在一个Where语句中或多个变量中。
谢谢。
更新 :这是我所拥有的。 我忘了提到表需要从不同的存储库加载。
var categoriesToLoad = new List<int>();
// table A
var tableACount = repo.ReadAll()
.GroupBy(n => n.CategoryID)
.Select(n => new
{
CategoryID = n.Key,
CountA = n.Count()
}
)
.OrderBy(n => n.CategoryID);
// table B
var tableBCount = repoTableB.ReadAll()
.GroupBy(n => n.CategoryID)
.Select(n => new
{
CategoryID = n.Key,
CountB = n.Count()
}
)
.OrderBy(n => n.CategoryID);
// check count
foreach (var itemTableATableB in tableBCount)
{
foreach (var itemTableA in tableACount)
{
if (itemTableA.CategoryID == itemTableATableB.CategoryID && itemTableA.CountA < itemTableATableB.CountB)
{
categoriesToLoad.Add((int)itemTableATableB.CategoryID);
}
}
}
var test = myRepo.ReadAll().Where(t => categoriesToLoad.Contains(t.Category_id))
除了安静的长代码之外,由于if (itemTableA.CategoryID == itemTableATableB.CategoryID
我还丢失了值,因为表B中的某些类别ID在表A中不存在(但我也需要这些ID)。
尝试这样的事情:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication87
{
class Program
{
static void Main(string[] args)
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("CategoryID", typeof(int));
dt1.Columns.Add("ProductID", typeof(int));
dt1.Rows.Add(new object[] { 1,4});
dt1.Rows.Add(new object[] { 1,5});
dt1.Rows.Add(new object[] { 2,7});
DataTable dt2 = new DataTable();
dt2.Columns.Add("CategoryID", typeof(int));
dt2.Columns.Add("ProductID", typeof(int));
dt2.Rows.Add(new object[] { 1, 4 });
dt2.Rows.Add(new object[] { 2, 7 });
var lessRows = (from a in dt1.AsEnumerable().GroupBy(x => x.Field<int>("CategoryID"))
join b in dt2.AsEnumerable().GroupBy(x => x.Field<int>("CategoryID")) on a.Key equals b.Key
select new { a = a, b = b })
.Where(x => x.a.Count() > x.b.Count())
.ToList();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.