首页 > 解决方案 > 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 两次的情况下产生相同的结果?

标签: c#listperformancelinqsplit

解决方案


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];

推荐阅读