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

Dez*_*ndo 2 c# linq lambda custom-lists

这是你的假设.如果您有一个字符串列表,是否可以按该字符串中存在的给定字符对该列表进行排名?

考虑这个伪代码:

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("*"));
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我想重新排序列表,这样每当字符串中出现星号(*)时,它就会将该字符串放在列表的顶部.

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

Jam*_*mes 13

假设你想根据位置优先考虑字符串*,你可以这样做

bunchOfStrings.OrderByDescending(x => x.IndexOf("*"))
Run Code Online (Sandbox Code Playgroud)

使用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;
});
Run Code Online (Sandbox Code Playgroud)

注意 - 9999只是我们可以假设IndexOf永远不会超过的一些非常值

查看实例