我有一个看起来像这样的类:
{
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public int DepId{ get; set; }
}
}
我的列表折叠的数据如下所示:
ID | Name | CategoryId | DepId
---------------------------------------
1 | Post | 1 | 1
2 | Post | 1 | 2
3 | Printer | 2 | 1
4 | Printer | 2 | 3
5 | Post | 3 | 3
6 | Printer | 2 | 1
此数据包含某些类别的 Access 数据。
我想得到的是 2 个(或更多)部门的通用类别
如果用户选择他想要 id=1 的部门类别,那么他应该得到 id 1 和 3 的元素,但是如果他想要部门 1 和 3 的类别,他应该得到元素 4 和 6。
对于 DepId IN(1,3) 我想得到这个结果:
Name | CategoryId
----------------------
Printer | 2
像 SQL 中的 JOIN 之类的东西。
我能够在 sql 中对其进行编码:
SELECT * FROM(
SELECT
C.Cat_Id AS Id,
MAX(C.Name) AS Name,
FROM
Categories_Access AS CA (NOLOCK)
JOIN dbo.Categories AS C (NOLOCK) ON C.Cat_Id = CA.Cat_Id
WHERE
CA.DepId IN (1,3)
GROUP BY C.Cat_Id
HAVING COUNT(*)=2
) A ORDER BY A.Name
现在我想在 C# 中做同样的事情。
编辑 这是我的尝试:
var cat = new List<Category>();
cat.Add(new Category {Id = 1, CategoryId = 1, Name = "Post", DepId = 1});
cat.Add(new Category {Id = 2, CategoryId = 1, Name = "Post", DepId = 2});
cat.Add(new Category {Id = 3, CategoryId = 2, Name = "Printer", DepId = 1});
cat.Add(new Category {Id = 4, CategoryId = 2, Name = "Printer", DepId = 3});
cat.Add(new Category {Id = 5, CategoryId = 3, Name = "Another", DepId = 3});
cat.Add(new Category {Id = 6, CategoryId = 2, Name = "Printer", DepId = 1});
cat.Add(new Category {Id = 7, CategoryId = 4, Name = "Else", DepId = 1});
var ids = new List<int> {1, 2};
var Query = from p in cat.Where(i => ids.Contains(i.DepId)).GroupBy(p => p.CategoryId)
select new
{
count = p.Count(),
p.First().Name,
p.First().CategoryId
};
我需要做的只是选择具有 count=ids.Count 的项目。
我的结局版本(基于@roughnex 的回答):
private static IEnumerable<Cat> Filter(IEnumerable<Category> items, List<int> ids)
{
return items.Where(d => ids.Contains(d.DepId))
.GroupBy(g => new { g.CategoryId, g.Name })
.Where(g => g.Count() == ids.Count)
.Select(g => new Cat { Id = g.Key.CategoryId, Name = g.Key.Name });
}