所以假設我們有一個停車場(表示為字典<int,bool> :每個停車場都有它的 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-free, 1-free, 2-filled , 3-free 結果將是兩個串列:第一個將包含=> 0 ,1 第二個將包含=> 3這些是連續免費停車場的串列。
public List<List<int>> ConsecutiveParkingLotFree(int numberOfConsecutive){}
uj5u.com熱心網友回復:
你總是可以撰寫自己的輔助函式來做這樣的事情。例如
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 轉換時,將回傳并重新創建串列。我希望有更緊湊的方法來撰寫這樣的函式,但它應該可以完成這項作業。
uj5u.com熱心網友回復:
您可以在此處應用 GroupWhile 解決方案。
parking.Where(X => X.Value)
.Select(x => x.Key)
.GroupWhile((x, y) => y - x == 1)
.ToList()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381796.html
下一篇:將給定的SQL查詢轉換為LINQ
