c# - C# 如何使用 LINQ 将列表一分为二
问题描述
我正在尝试使用 LINQ 将列表拆分为两个列表,而无需两次迭代“主”列表。一个 List 应包含 LINQ 条件为true的元素,而另一个 List 应包含所有其他元素。这是可能吗?
现在我只使用两个 LINQ 查询,从而迭代(巨大的)主列表两次。
这是我现在正在使用的(伪)代码:
List<EventModel> events = GetAllEvents();
List<EventModel> openEvents = events.Where(e => e.Closer_User_ID == null);
List<EventModel> closedEvents = events.Where(e => e.Closer_User_ID != null);
是否可以在不重复原始 List 两次的情况下产生相同的结果?
解决方案
You can use ToLookup
extension method as follows:
List<Foo> items = new List<Foo> { new Foo { Name="A",Condition=true},new Foo { Name = "B", Condition = true },new Foo { Name = "C", Condition = false } };
var lookupItems = items.ToLookup(item => item.Condition);
var lstTrueItems = lookupItems[true];
var lstFalseItems = lookupItems[false];
推荐阅读
- python - 要求输入直到确切的字符串是输入问题
- c# - Applitools.EyesSetViewportSizeException :无法设置所需的视口大小。似乎是一个舍入错误
- leaflet - Leaflet clearLayers 正在冻结浏览器
- list - Flutter:将firestore快照转换为streambuilder中的列表
- python - QGraphicsView 开始时大小错误
- python - Python 版本 3 - ValueError: no enough values to unpack (expected 2, got 1)
- python - Pandas python将列表转换为数据框并计算出现次数
- python - 如何在 Python 中保存数据框表?
- google-apps-script - 谷歌表格,更新信件库存数量
- javascript - 使用 DOM(篡改猴子)作为用户样式的暗模式切换开关