嘿,我正在嘗試找出在串列中獲取一段資料的最佳方式。根據他們的型別想象一下,我在串列中有以下資料:
public enum StepStatus {
Skipped,
NotStarted,
Completed,
}
public enum StepType
public class Steps {
StepStatus Status { get; set; }
StepType Type { get; set;}
// Other info
}
我有所有步驟及其狀態的串列
//Data
1, StepStatus.Skipped, StepType.Notification
2, StepStatus.Completed, StepType.Notification
3, StepStatus.NotStarted, StepType.Notification
4, StepStatus.NotStarted, StepType.Notification
5, StepStatus.NotStarted, StepType.Approval}
6, StepStatus.NotStarted, StepType.Notification
我想獲取所有未開始的通知,直到并包括第一次批準。所以我想要回傳串列的這一部分
3, StepStatus.NotStarted, StepType.Notification
4, StepStatus.NotStarted, StepType.Notification
5, StepStatus.NotStarted, StepType.Approval
我能想到的最簡單的方法是。
var firstApprovalStep = steps.FirstOrDefault(x => x.Status == StepStatus.NotStarted && x.Type == StepType.Approval);
if(null == firstApprovalStep)
{
//If there are no pending approvals left return the pending notfications
return steps.Reverse().TakeWhile(x => x.Status == StepStatus.NotStarted && x.Type == StepType.Notification);
}
//Find the element in the list with that index and grab all prior.
steps.GetNotStartedNotificationsPrior(firstStep);
我想知道是否有一種更簡單/更精明的方式來使用 linq 來抓取這個片段?
uj5u.com熱心網友回復:
由于我們知道您使用的是 aList<T>我們可以稍微作弊并使用源IEnumerable兩次而不會受到太多懲罰。
這是一個擴展方法:
public static IEnumerable<T> TakePast<T>(this IEnumerable<T> items, Func<T, bool> posFn) => items.Take(items.TakeWhile(i => !posFn(i)).Count() 1);
使用它,您可以執行以下操作:
return steps.Where(s => s.StepStatus == StepStatus.NotStarted)
.TakePast(s => s.StepType == StepType.Approval);
當然,這意味著您可以擴展擴展方法:
return steps.Where(s => s.StepStatus == StepStatus.NotStarted)
.Take(steps.Where(s => s.StepStatus == StepStatus.NotStarted).TakeWhile(s => s.StepType != StepType.Approval)).Count() 1);
我假設唯一的StepTypes 是因為你沒有定義.NotificationApprovalenum
這是一個列舉任何序列一次的通用實作:
public static IEnumerable<T> TakePast<T>(this IEnumerable<T> items, Func<T, bool> posFn) {
var ie = items.GetEnumerator();
while (ie.MoveNext()) {
yield return ie.Current;
if (posFn(ie.Current))
yield break;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467138.html
上一篇:一個類可以在C#中指向它自己嗎
