2013-04-22 57 views
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 

因为项目编号1具有的所有值{1,2,3,4}

+1

以及如果1中没有一个(1,2,3,4),比如说第4个,会出现什么情况。什么应该是预期的产出? – Tigran 2013-04-22 08:15:09

回答

0

如何:

var results = secondLists 
    .GroupBy(z => z.ID) 
    .Where(z => firstLists.All(z2 => z.Select(z3 => z3.EntitytID).Contains(z2))) 
    .SelectMany(z => z); 
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. 如果交叉点包含第一个列表的所有元素,它将把该组添加到您将返回的列表中。
相关问题