【问题标题】:C# - Sort list of strings by instances of a specified character?C# - 按指定字符的实例对字符串列表进行排序?
【发布时间】:2021-01-23 19:54:27
【问题描述】:

如果我想按指定字符的数量(在这种情况下说“b”)对字符串列表(比如 15 个字符串)进行排序,我该怎么做?不包含指定字符的字符串的顺序无关紧要。

例如:“amy”、“bob”、“lee”、“bret”,这应该是 排序如下:

  1. “鲍勃”
  2. 布雷特
  3. 艾米

我的猜测是我必须创建一个由 IComparer 继承的新类,但除此之外我不知道如何继续。有什么想法吗?

到目前为止的代码,如果重要的话:

List<string> str = new List<string>();

            for (int i = 0; i < 10; i++)
            {
                Console.Write("{0}: ", i + 1);
                str.Add(Console.ReadLine());               
            }

【问题讨论】:

  • 您在哪里尝试按照您需要的方式进行排序?

标签: c# list sorting collections


【解决方案1】:

确实可以使用类,但使用 linq 你可以问问自己是否真的需要

List<string> listOfNames = new List<string>();
listOfNames.Add("bob");
listOfNames.Add("bret");
listOfNames.Add("amy");
listOfNames.Add("lee");

// sort the string by the count of character of B or b
var sorted = listOfNames.OrderBy(name => name.Count(c => c == 'b' || c == 'B')).ToList();

【讨论】:

  • 这么简单,你看那个!非常感谢,谢谢。
【解决方案2】:

我认为使用 Linq 的答案是最清楚的,但您也可以使用比较器。并且使用 List.Sort 确实避免了创建新列表。

您可以专门为您的后计数字符创建自定义比较器。或者,您可以创建一个使用 lambda 的泛型。第二个更有趣,所以我会展示那个。

    class AnonymousComparer<T> : IComparer<T>
    {
        Func<T, T, int> compare;

        public AnonymousComparer(Func<T, T, int> compare)
        {
            this.compare = compare;
        }

        public int Compare([AllowNull] T x, [AllowNull] T y)
        {
            return this.compare(x, y);
        }

        public static implicit operator AnonymousComparer<T>(Func<T,T,int> compare) 
            => new AnonymousComparer<T>(compare);
    }

一旦你有了它,你就可以提供一个 lambda 来进行比较。这使用了一个简单的局部函数来进行字符比较。

    static void Main(string[] _)
    {
        List<string> myStrings = new List<string>(
                                new string[] { "one", "two", "three", "four", "five", });

        bool IsMyLetter(char ch) => ch == 'e' || ch == 'E';

        myStrings.ForEach((s) => Console.WriteLine(s));

        Console.WriteLine("\n\nafter sort\n");

        myStrings.Sort((lhs, rhs) => rhs.Count(x => IsMyLetter(x)) - lhs.Count(x => IsMyLetter(x)));

        myStrings.ForEach((s) => Console.WriteLine(s));
    }

【讨论】:

  • 感谢您展示这个更深入的代码,非常有趣的解决方法。
猜你喜欢
  • 2021-06-10
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 2014-04-15
  • 2014-02-21
  • 2012-04-03
相关资源
最近更新 更多