[英]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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.