【问题标题】:Sort list where specific character exists within string字符串中存在特定字符的排序列表
【发布时间】:2014-06-19 11:16:57
【问题描述】:

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

考虑这个伪代码:

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 或类似方法,有什么想法吗?

【问题讨论】:

  • 好吧,您可以使用 OrderBy 并提供一个自定义的 IComparer&lt;string&gt; 实现来进行比较。

标签: c# linq lambda custom-lists


【解决方案1】:

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

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

使用OrderByDescending,因为对于不包含* 的字符串,它们将返回-1


实际上,进一步研究它并不能直接使用IndexOfOrderByDescending 将通过最高 排名的索引来工作,在您的情况下它将是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 永远不会超过的任意值

See live example

【讨论】:

  • 这比我即将发布的答案要好。
  • 太棒了,这就是我所追求的 :) 谢谢!只是在等待 SO 计时器倒计时,这样我就可以标记答案了。
【解决方案2】:

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

Contains 返回布尔值 - 所以你是按真或假排序。由于 true 为 1 且 0 为 false - 您将它们从您想要的倒序排列。所以你想要OrderByDescending:

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

排序 1 -> 0。

Click here for live example on IDEOne.

【讨论】:

  • 谢谢西蒙,非常感谢!
  • 这仅在包含* 的字符串的顺序正确时才有效。例如,如果 this should be *somewhere near the top 在列表中出现在 this *SHOULD be at the top 之前,那么它们将无法正确排序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
  • 2020-06-02
  • 2020-07-17
  • 1970-01-01
相关资源
最近更新 更多