c# - 使用 LINQ 从列表中删除未包含的所有项目

标签 c# linq-to-sql linq-to-entities

我有一个通用列表ItemList,其中如果每个ListID不包含所有可能的ItemID,那么我想删除它们从列表中。

我将在下面用数据的简化版本进行说明:

MaxItemID = 4

ListID       ItemID       

   1            1       
   2            1 
   2            2 
   2            3
   2            4
   3            1
   3            2 
   4            1
   4            2
   4            3
   4            4
   5            1
   5            2

我想要的数据是:

ListID       ItemID       

   2            1 
   2            2 
   2            3
   2            4
   4            1
   4            2
   4            3
   4            4

我昨天问了一个与 SQL 相关的类似问题,并得到了使用 Exists 的答案,这很好,但我后来发现最大项目数可能会有所不同,而且我想我更喜欢使用 linq。我认为使用 distinct().Count() 技术可以工作,但到目前为止还没有成功,而且听起来这也不是最有效的方法。

非常感谢

最佳答案

int distinctIDs = items.Select(x => x.ItemID).Distinct().Count();
var newList = items
    .GroupBy(x => x.ListID)
    .Where( x => x.Select(y=>y.ItemID).Distinct().Count() ==  distinctIDs)
    .SelectMany(x => x.ToList())
    .ToList();

关于c# - 使用 LINQ 从列表中删除未包含的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9111768/

相关文章:

c# - Sql 到 Linq 嵌套连接

c# - foreach block 缺少结束字符 "}"

c# - 如何从代码动态填充ListPreference?

linq-to-sql - 找出正在更新的字段

c# - 如何仅在必要时使用 ADO.NET Entity Framework 加载 varbinary(max) 字段?

c# - c sharp exe打开时应该要求 "run as administrator"提示

c# - 无法将类型 'System.Collections.Generic.IEnumerable<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<modelClass>

asp.net-mvc - 创建新 Controller 时出现错误 :'Unsupported context type'

c# - 为什么 IQueryable 上的 .Where() 根据是否将 Lamba 或 Func<T,Tresult> 作为参数传递返回不同的类型

linq-to-sql - linq to entities vs fluent nhibernate vs linq to sql(帮助)