C# 我想要第二个列表中的项目,其中包含第一个列表中的所有项目

C# 我想要第二个列表中的项目,其中包含第一个列表中的所有项目,c#,c#-4.0,C#,C# 4.0,下面是我的代码的样子 List<Entity> lists = CacheManager.GetAllEntity(); List<long> firstLists = lists .Select <Entity,long>(x=>x.ID).ToList<long>(); List<Entity2> secondLists = CacheManager.GetAllEntity2(); 现在假设firstsLists包含{1,

下面是我的代码的样子

List<Entity> lists = CacheManager.GetAllEntity();
List<long> firstLists = lists .Select <Entity,long>(x=>x.ID).ToList<long>();
List<Entity2> secondLists = CacheManager.GetAllEntity2();
现在假设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}

那么:

var results = secondLists
    .GroupBy(z => z.ID)
    .Where(z => firstLists.All(z2 => z.Select(z3 => z3.EntitytID).Contains(z2)))
    .SelectMany(z => z);
var itemsGroupedById=SecondList.GroupBy(item=>item.id,item=>item.ToList();
var listToReturn=新列表();
foreach(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(组);
}
}
返回列表返回;
这将执行以下操作-

  • 按ID对第二个列表中的所有项目进行分组
  • 在每个组中,它将与该组中的实体ID列表以及第一个组中的实体ID列表相交
  • 如果交叉点具有第一个列表中的所有元素,它会将该组添加到您将返回的列表中

  • 如果1中的一个没有(1,2,3,4)中的一个,比如说第4个。预期输出应该是什么?
    var results = secondLists
        .GroupBy(z => z.ID)
        .Where(z => firstLists.All(z2 => z.Select(z3 => z3.EntitytID).Contains(z2)))
        .SelectMany(z => z);
    
    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;