3

这是我的代码的样子

List<Entity> lists = CacheManager.GetAllEntity();
List<long> firstLists = lists .Select <Entity,long>(x=>x.ID).ToList<long>();
List<Entity2> secondLists = CacheManager.GetAllEntity2();

其中 Entity2 看起来像:

public class Entity2
{
    public long ID;     
    public long EntitytID;
}

现在假设 firstsLists 包含{1,2,3,4}. 第二个包含

ID   EntitytID
1    1 
1    2
1    3
1    4
2    1
2    4
3    1
4    2
5    4

那么我的输出应该给我

ID   EntitytID
1    1 
1    2
1    3
1    4

因为项目 id 1 具有所有值{1,2,3,4}

4

2 回答 2

0
var itemsGroupedById = SecondList.GroupBy(item => item.id, item => item).ToList();
var listToReturn = new List<Entity2>();
foreach(var group in itemsGroupedById)
{
    var id = group.Key;
    var entityIdsInThisGroup = group.Select(items => items.EntityId).ToList();
    var intersection = entityIdsInThisGroup.Intersect(FirstList).ToList();
    if(intersection.Count == FirstList.Count)
    {
        listToReturn.Add(group);
    }
}
return listToReturn;

这将执行以下操作 -

  1. 按 ID 对第二个列表中的所有项目进行分组。
  2. 在每个组中,它将与该组中的实体 ID 列表以及您的第一个组中的实体 ID 列表相交。
  3. 如果交集包含您的第一个列表的所有元素,它将将该组添加到您将返回的列表中。
于 2013-04-22T08:29:31.470 回答
0

怎么样:

var results = secondLists
    .GroupBy(z => z.ID)
    .Where(z => firstLists.All(z2 => z.Select(z3 => z3.EntitytID).Contains(z2)))
    .SelectMany(z => z);
于 2013-04-22T08:20:43.943 回答