Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 字符串中存在特定字符的排序列表_C#_Linq_Lambda_Custom Lists - Fatal编程技术网

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

C# 字符串中存在特定字符的排序列表,c#,linq,lambda,custom-lists,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("T

这里有一个假设。如果要有一个字符串列表,是否可以根据该字符串中存在的给定字符对该列表进行排序

考虑以下伪代码:

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("*"));
List bunchOfStrings=新列表;
bunchOfStrings.Add(“这不应该在顶部”);
Add(“这也不应该在顶部”);
bunchOfStrings.Add(“这也不应该在顶部”);
bunchOfStrings.Add(“这个*应该在顶部”);
bunchOfStrings.Add(“这不应该在顶部”);
bunchOfStrings.Add(“这应该是*靠近顶部的某个地方”);
OrderBy(x=>x.Contains(“*”);
在上面的代码中,我想对列表重新排序,这样每当字符串中出现星号(*)时,它就会将该字符串放在列表的顶部


如果使用LINQ或类似工具也能做到这一点,你有什么想法吗?

假设你想根据
*
的位置对字符串进行优先级排序,你可以这样做

bunchOfStrings.OrderByDescending(x => x.IndexOf("*"))
使用
OrderByDescending
,因为对于不包含
*
的字符串,它们将返回
-1


实际上,进一步研究这一点,使用
IndexOf
将无法直接运行
OrderByDescending
将通过查找排名最高的索引来工作,在您的情况下,索引将是
这应该是*靠近顶部的某个地方
,而不是
这*应该在顶部
,因为
*
在该字符串中有更高的索引

因此,要让它发挥作用,您只需稍微操纵一下排名,然后使用
OrderBy

bunchOfStrings.OrderBy(x => {
    var index = x.IndexOf("*");
    return index < 0 ? 9999 : index;
});
bunchOfStrings.OrderBy(x=>{
var指数=x.IndexOf(“*”);
回归指数<0?9999:指数;
});
注意-
9999
只是一个我们可以假设
IndexOf
永远不会超过的aribtrary值


如果
包含您想要使用的内容

包含
返回布尔值-因此您按true或false排序。由于true为1,0为false,因此您正在按照所需顺序向后排序。所以您需要降序排序

bunchOfStrings.OrderByDescending(x => x.Contains("*"))
排序为1->0


好吧,你可以使用
OrderBy
并提供一个自定义的
icomparaer
实现来进行比较。这比我即将发布的答案要好。太棒了,这正是我想要的:)谢谢!只需等待SO计时器倒数,以便我可以标记答案。谢谢Simon,非常感谢!但这仅在包含
*
的字符串顺序正确时才起作用。例如,如果
这应该是*在列表中靠近顶部的某个地方
出现在
这*应该在顶部
之前,那么它们将无法正确排序。