簡體   English   中英

排序列表中特定字符存在的列表

[英]Sort list where specific character exists within string

這是你的假設。 如果您有一個字符串列表,是否可以按該字符串中存在的給定字符對該列表進行排名?

考慮這個偽代碼:

List<String> bunchOfStrings = new List<String>;
bunchOfStrings.Add("This should not be at the top");
bunchOfStrings.Add("This should not be at the top either");
bunchOfStrings.Add("This should also not be at the top");
bunchOfStrings.Add("This *SHOULD be at the top");
bunchOfStrings.Add("This should not be at the top");
bunchOfStrings.Add("This should be *somewhere close to the top");

buncOfStrings.OrderBy(x => x.Contains("*"));

在上面的代碼中,我想重新排序列表,這樣每當字符串中出現星號(*)時,它就會將該字符串放在列表的頂部。

如果LINQ或類似的話甚至可能有任何想法?

假設您想根據*的位置確定字符串的優先級,您可以這樣做

bunchOfStrings.OrderByDescending(x => x.IndexOf("*"))

使用OrderByDescending因為對於不包含*的字符串,它們將返回-1


實際上,進一步研究這一點並不能直接與IndexOf OrderByDescending將通過獲得排名最高的索引來工作,在你的情況下, this should be *somewhere close to the top而不是this *SHOULD be at the top因為*在該字符串中具有更高的索引。

所以要讓它工作,你只需稍微操縱排名並使用OrderBy

bunchOfStrings.OrderBy(x => {
    var index = x.IndexOf("*");
    return index < 0 ? 9999 : index;
});

注意 - 9999只是一些我們可以假設IndexOf永遠不會超過的aribtrary值

查看實例

如果Contains是你想要使用的..

Contains返回布爾值 - 因此您按順序排序為true或false。 因為true是1而0是假的 - 你從他們想要的東西向后排序。 所以你想要OrderByDescending

bunchOfStrings.OrderByDescending(x => x.Contains("*"))

哪種排序1 - > 0。

單擊此處獲取IDEOne上的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM