[英]using Array.sort too sort a string
因此,我想嘗試制作一個“程序”,使我的密碼輸出很快在我公司的AD中過期。 但是我遇到了一個小問題。 當我調用“ array.sort(array)”時,因為它是一個包含時間跨度和名稱的字符串,所以似乎將人們分組還剩下多長時間,但沒有首先將最小的數字分組。 任何人都有關於如何解決此問題的想法,因為它是字符串? *我知道我是一個業余程序員,代碼糟糕,難以閱讀!
foreach (Principal p in grp.GetMembers(false))
{
TimeSpan tidtilbage = timeToExpire.GetTimeRemainingUntilPasswordExpiration(DOMAIN, p.SamAccountName);
TimeSpan under14 = new TimeSpan(14, 00, 00, 00);
TimeSpan ikkeMinus10 = new TimeSpan(-10, 00, 00, 00);
if (tidtilbage < under14 && tidtilbage > ikkeMinus10)
{
string lines = tidtilbage.ToString("%d") + " dag(e)" + " " + tidtilbage.ToString("%h") + " time(r)" + " - " + p.SamAccountName.ToUpper() + " - " + p.DisplayName + "\n\n";
sorted[i] = lines;
Array.Sort(sorted);
i++;
}
else
continue;
}
foreach (var item in sorted)
{
if (item == null || item == "")
continue;
else
{
Console.WriteLine("{0}", item);
myWriter.WriteLine("{0}", item);
}
}
myWriter.Close();
這是我得到的輸出:
因此,您想按最先出現的數值對字符串進行排序嗎? 然后,您需要使用int.Parse
將該子字符串轉換為int
。 您可以使用LINQ的OrderBy
進行訂購:
sorted = sorted
.OrderBy(s => int.Parse(new String(s.TakeWhile(Char.IsDigit).ToArray())))
.ToArray();
請注意,如果字符串不是以整數開頭,則將導致異常。
但是在這種情況下,最好也存儲原始的TimeSpan
,這樣更容易排序。
TimeSpan under14 = new TimeSpan(14, 00, 00, 00);
TimeSpan ikkeMinus10 = new TimeSpan(-10, 00, 00, 00);
sorted = grp.GetMembers(false)
.Select(account => new
{
tidtilbage = timeToExpire.GetTimeRemainingUntilPasswordExpiration(DOMAIN, account.SamAccountName),
account
})
.Select(x => new
{
x.tidtilbage,
lines = x.tidtilbage.ToString("%d") + " dag(e)" + " " + x.tidtilbage.ToString("%h") + " time(r)" + " - " + x.account.SamAccountName.ToUpper() + " - " + x.account.DisplayName + "\n\n"
})
.Where(x => x.tidtilbage < under14 && x.tidtilbage > ikkeMinus10)
.OrderBy(x => x.tidtilbage)
.Select(x => x.lines)
.ToArray()
OP稍有下降,但由於tidtilbage
已經是TimeSpan
類型。 您還可以使用List
,而不是Array
並執行更清晰的操作。
示例示例:
List<TimeSpan> tsList = new List<TimeSpan>();
for (int i = 1; i <= 10; i++)
{
Random rnd = new Random(i);
TimeSpan ts = new TimeSpan(0,0,rnd.Next(10000));
tsList.Add(ts);
}
//This is the line you will need
tsList = tsList.OrderBy(x => x.TotalSeconds).ToList();
您所有的tidtilbage
都有一個TotalSeconds
屬性,您可以輕松地OrderBy()
。
只是給你一個主意。
@TimSchmelter
foreach (Principal p in grp.GetMembers(false))
{
TimeSpan tidtilbage = timeToExpire.GetTimeRemainingUntilPasswordExpiration("cv.local", p.SamAccountName);
TimeSpan under14 = new TimeSpan(14, 00, 00, 00);
TimeSpan ikkeMinus10 = new TimeSpan(-10, 00, 00, 00);
sorted = grp.GetMembers(false)
.Select(x => new
{
tidtilbage = timeToExpire.GetTimeRemainingUntilPasswordExpiration("cv.local", p.SamAccountName),
lines = tidtilbage.ToString("%d") + " dag(e)" + " " + tidtilbage.ToString("%h") + " time(r)" + " - " + p.SamAccountName.ToUpper() + " - " + p.DisplayName + "\n\n"
})
.Where(x => x.tidtilbage < under14 && x.tidtilbage > ikkeMinus10)
.OrderBy(x => x.tidtilbage)
.Select(x => x.lines)
.ToArray();
i++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.