符合列表中条件的连续元素的子列表 c# linq
Sublists of consecutive elements that fit a condition in a list c# linq
所以假设我们有一个停车场(表示为字典:
每个停车场都有它的 ID 和一个布尔值(免费,已满)。
这样:
Dictionary<int,bool> parking..
parking[0]= true // means that the first parking lot is free
我的问题是我想获取符合以下条件的连续元素的所有子列表:停车场免费。
首先我可以很容易地得到适合这种情况的元素:
parking.Where(X => X.Value).Select(x => x.Key).ToList();
但是我不知道如何使用 linq 操作来获取匹配的第一个生成列表。
我可以在没有数千个 foreach-while 循环逐一检查迭代的情况下做到这一点吗,有没有更简单的 linq 方法?
该方法获取连续空闲车位列表
数据:
0-免费,
1-免费,
2-填充,
3免
结果将是两个列表:
第一个将包含 => 0 ,1
第二个将包含 => 3
这些是连续的免费停车场列表。
public List<List<int>> ConsecutiveParkingLotFree(int numberOfConsecutive){}
您始终可以编写自己的辅助函数来执行此类操作。例如
public static IEnumerable<List<T>> GroupSequential<T, TKey>(
this IEnumerable<T> self,
Func<T, bool> condition)
{
var list = new List<T>();
using var enumerator = self.GetEnumerator();
if (enumerator.MoveNext())
{
var current = enumerator.Current;
var oldValue = condition(current);
if (oldValue)
{
list.Add(current);
}
while (enumerator.MoveNext())
{
current = enumerator.Current;
var newValue = condition(current);
if (newValue)
{
list.Add(current);
}
else if (oldValue)
{
yield return list;
list = new List<T>();
}
oldValue = newValue;
}
if (list.Count > 0)
{
yield return list;
}
}
}
这会将所有具有真值的项目放入列表中。当遇到 true->false 转换时,返回并重新创建列表。我希望有更紧凑的方法来编写这样的函数,但它应该可以完成工作。
您可以应用 GroupWhile 解决方案 here。
parking.Where(X => X.Value)
.Select(x => x.Key)
.GroupWhile((x, y) => y - x == 1)
.ToList()
所以假设我们有一个停车场(表示为字典
Dictionary<int,bool> parking..
parking[0]= true // means that the first parking lot is free
我的问题是我想获取符合以下条件的连续元素的所有子列表:停车场免费。
首先我可以很容易地得到适合这种情况的元素:
parking.Where(X => X.Value).Select(x => x.Key).ToList();
但是我不知道如何使用 linq 操作来获取匹配的第一个生成列表。 我可以在没有数千个 foreach-while 循环逐一检查迭代的情况下做到这一点吗,有没有更简单的 linq 方法?
该方法获取连续空闲车位列表 数据: 0-免费, 1-免费, 2-填充, 3免 结果将是两个列表: 第一个将包含 => 0 ,1 第二个将包含 => 3 这些是连续的免费停车场列表。
public List<List<int>> ConsecutiveParkingLotFree(int numberOfConsecutive){}
您始终可以编写自己的辅助函数来执行此类操作。例如
public static IEnumerable<List<T>> GroupSequential<T, TKey>(
this IEnumerable<T> self,
Func<T, bool> condition)
{
var list = new List<T>();
using var enumerator = self.GetEnumerator();
if (enumerator.MoveNext())
{
var current = enumerator.Current;
var oldValue = condition(current);
if (oldValue)
{
list.Add(current);
}
while (enumerator.MoveNext())
{
current = enumerator.Current;
var newValue = condition(current);
if (newValue)
{
list.Add(current);
}
else if (oldValue)
{
yield return list;
list = new List<T>();
}
oldValue = newValue;
}
if (list.Count > 0)
{
yield return list;
}
}
}
这会将所有具有真值的项目放入列表中。当遇到 true->false 转换时,返回并重新创建列表。我希望有更紧凑的方法来编写这样的函数,但它应该可以完成工作。
您可以应用 GroupWhile 解决方案 here。
parking.Where(X => X.Value)
.Select(x => x.Key)
.GroupWhile((x, y) => y - x == 1)
.ToList()