头发卷卷 發表於 2024-1-1 12:31:00

【C# 技术】C# 常用排序方式

<blockquote>
<div><b>
<font color="red" size="3"> 前言</font>
</b></div>
<p> 在最近的项目中经常会对C#中的数据进行排序,对于基本数据类型,其排序方式比较简单,只需要调用内置算法即可实现,但对于<code>自定义数据类型</code>以及<code>自定义排序规则</code>的情况实现起来就比较麻烦,所以在本文章中将详细介绍一下在中C#中如何对数据进行排序。</p>
<div><b>
<font color="#0000FF" size="3"> 应用技术:</font>
<font color="black" size="2">LINQ; Array.Sort();</font>
</b></div>
</blockquote>
<h1 id="1-常规数据排序">1. 常规数据排序</h1>
<h2 id="11-使用sort排序">1.1 使用Sort排序</h2>
<p>     对于系统内置数据,我们可以使用<code>Sort</code>方法直接进行排序,默认是采用正序进行排序,此处提供了三种方式:</p>
<ul>
<li>方式一:使用默认的<code>Sort()</code>方法直接就可以进行排序。</li>
<li>方式二:使用<code>Sort()</code>方法并添加回调函数,回调函数调用数据类型<code>CompareTo()</code>方法。</li>
<li>方式三:使用<code>Sort()</code>方法并添加回调函数,回调函数进行自定义,此处采用三目运算符写了个简单的方法。</li>
</ul>
<pre><code class="language-csharp">static void test_general_sort()
{
    int[] data = { 89, 63, 48, 62, 75, 663, 45, 359, 42 };
    // 1. 方式一
    Array.Sort(data);
    // 2. 方式二
    Array.Sort(data, (x, y) =&gt; x.CompareTo(y));
    // 3. 方式三
    Array.Sort(data, (x, y) =&gt; x &gt; y ? 1 : -1);
    print_array(data);
}
</code></pre>
<p><img src="https://files.mdnice.com/user/53424/e73d0271-c825-4758-ad3b-ca510165b4c7.png"></p>
<p>     如果是想进行逆序排序,最简单的方式就是将正序排列的数组进行一次反转即可,不然的话就是改变方法二以及方法三的回调函数输出,如下面代码所示。</p>
<pre><code class="language-csharp">static void test_general_sort_()
{
    int[] data = { 89, 63, 48, 62, 75, 663, 45, 359, 42 };
    // 1. 方式一
    Array.Sort(data);
    Array.Reverse(data);
    // 2. 方式二
    Array.Sort(data, (x, y) =&gt; y.CompareTo(x));
    // 3. 方式三
    Array.Sort(data, (x, y) =&gt; x &gt; y ? -1 : 1);
    print_array(data);
}
</code></pre>
<p><img src="https://files.mdnice.com/user/53424/715743bd-9c71-4919-9e0e-c4c921809db5.png"></p>
<h2 id="12-使用linq语句进行排序">1.2 使用LINQ语句进行排序</h2>
<p>     然后我们介绍一下使用LINQ语句进行排序,LINQ是一组用于C#和Visual Basic语言的扩展。它允许编写C#或者Visual Basic代码以查询数据库相同的方式操作内存数据。在此处我们可以使用两种方式实现:</p>
<ul>
<li>方式一:使用原生的LINQ语句进行查询,此处主要通过自己写LINQ语句;</li>
<li>方式二:使用封装好的方法<code>OrderBy()</code>,该方法使用比较简单,可以直接调用对应大方法即可。</li>
</ul>
<pre><code class="language-csharp">static void test_general_linq()
{
    int[] data = { 89, 63, 48, 62, 75, 663, 45, 359, 42 };
    // 1. 方式一
    IEnumerable&lt;int&gt; query = from d in data
                           orderby d
                           select d;
    // 2. 方式二
    query = data.OrderBy(x =&gt; x);
    print_array(query);
}
</code></pre>
<p>    如果要项进行逆序排序,此处可以添加<code>descending</code>关键字进行设定,或者直接使用<code>OrderByDescending()</code> 方法。</p>
<pre><code class="language-csharp">static void test_general_linq_()
{
    int[] data = { 89, 63, 48, 62, 75, 663, 45, 359, 42 };
    // 1. 方式一
    IEnumerable&lt;int&gt; query = from d in data
                           orderby d descending
                           select d;
    // 2. 方式二
    query = data.OrderByDescending(x =&gt; x);
    print_array(query);
}
</code></pre>
<h2 id="13-多条件排序">1.3 多条件排序</h2>
<p>    在实际使用时,我们可能会遇到多条件排序,即第一个条件相等时时,在采用第二个条件排序,如果遇到这种情况,我们处理起来可能就比较麻烦。如下面代码所示,对于一个字符串数组,我想首先按照字符串长度进行排序,如果字符串长度相等,就按照首字母进行排序。实现方式如下所示:</p>
<pre><code class="language-csharp">static void test_general_sort_more()
{
    string[] words = { "the", "quick", "brown", "fox", "jumps", "and" };
    Array.Sort&lt;string&gt;(words, (x, y) =&gt;
    {
      if (x.Length &gt; y.Length) { return 1; }
      else if (x.Length == y.Length)
      {
            if (x.Substring(0, 1) &gt; y.Substring(0, 1)) { return 1; }
            else { return -1; }
      }
      else { return -1; }
    });
    print_array(words);
}
</code></pre>
<p>    在上面这段代码中,我们主要是使用了<code>Lambda</code>表达式创建了一个委托函数,在这个委托函数里,我们按照排序要求,对其进行了定义,主要是对返回值的条件进行了定义,最后排序结果输出为:</p>
<pre><code class="language-bash">Array = {the, quick, brown, fox, jumps, and}
Array = {and, fox, the, brown, jumps, quick}
</code></pre>
<p>    不过该方式看起来实现是比较复杂的,对于大多是人来说,可能很难看懂,所以此处我们向大家展示一个比较简单的方式,就是使用LINQ语句进行多条件排序,如下面代码所示:</p>
<pre><code class="language-csharp">static void test_general_linq_more()
{
    string[] words = { "the", "quick", "brown", "fox", "jumps", "and" };
    // 1. 方式一
    IEnumerable&lt;string&gt; query = from word in words
                              orderby word.Length, word.Substring(0, 1)
                              select word;
    // 2. 方式二
    query = words.OrderBy(x =&gt; x.Length).ThenBy(x =&gt; x.Substring(0, 1));
    print_array(query);
}
</code></pre>
<p>    使用LINQ语句进行排序看起来就比较简单了,上面依旧是展示了两种方式,对于多条件排序,如果使用自定义LINQ语句排序就只需要在上一个条件后增加次要条件即可;如果使用封装后的LINQ语句,就可以在<code>OrderBy()</code>增加<code>ThenBy()</code>方法添加第二个条件。如果想实现反向排序,实现方式与上文相同。</p>
<h1 id="2-自定义数据排序">2. 自定义数据排序</h1>
<p>    下面我们进行自定义数据进行排序,如下面代码所示,我们在此处定义了一个<code>        Person</code>类,并且继承了<code>IComparable&lt;Person&gt;</code>接口,该接口主要是用于后面调用<code>Sort</code>方法所必需的接口。</p>
<pre><code class="language-csharp">class Person : IComparable&lt;Person&gt;
{
    public string name { get; set; }
    public int age { get; set; }
    public int id { get; set; }

    public int CompareTo(Person? other)
    {
      if (this.age &gt; other.age) { return 1; }
      else { return -1; }
    }
    public override string ToString()
    {
      return "(id: " + id + ", name: " + name + ", age: " + age + ")";
    }
};
</code></pre>
<h2 id="21-使用sort排序">2.1 使用Sort排序</h2>
<p>     对于自定义数据,我们可以使用<code>Sort</code>方法直接进行排序,默认是采用正序进行排序,此处提供了三种方式:</p>
<ul>
<li>方式一:使用默认的<code>Sort()</code>方法直接就可以进行排序,但是需要自定义数据继承<code>IComparable&lt;T&gt;</code>接口</li>
<li>方式二:使用<code>Sort()</code>方法并添加回调函数,回调函数调用数据类型<code>CompareTo()</code>方法,该方法可以进行自定义。</li>
<li>方式三:使用<code>Sort()</code>方法并添加回调函数,回调函数进行自定义,此处采用三目运算符写了个简单的方法,该方式无需继承继承<code>IComparable&lt;T&gt;</code>接口以及在自定义数据中添加比较函数。</li>
</ul>
<p>     代码如下所示:</p>
<pre><code class="language-csharp">static void test_person_sort()
{
    List&lt;Person&gt; list = new List&lt;Person&gt;()
    {
                new Person(){name="a",age=15,id=1 },
                new Person(){name="b",age=12,id=2 },
                new Person(){name="c",age=14,id=3 },
                new Person(){name="d",age=12,id=4 },
                new Person(){name="e",age=14,id=5 },
                new Person(){name="f",age=12,id=6 },
                new Person(){name="g",age=15,id=7 },
            };
    print_array(list);

    // 1. 方式一
    list.Sort();
    // 2. 方式二
    list.Sort((x, y) =&gt; x.CompareTo(y));
    // 3. 方式三
    list.Sort((x, y) =&gt; x.age &gt; y.age ? 1 : -1);

    print_array(list);

}
</code></pre>
<p>     排序后结果输出为:</p>
<p><img src="https://files.mdnice.com/user/53424/7e8a8d6b-7532-4726-bd02-a81f198a6a39.png"></p>
<p>     如果想进行逆序排序,需要修改一下比较规则</p>
<pre><code class="language-csharp">static void test_person_sort_()
{
    List&lt;Person&gt; list = new List&lt;Person&gt;()
    {
                new Person(){name="a",age=15,id=1 },
                new Person(){name="b",age=12,id=2 },
                new Person(){name="c",age=14,id=3 },
                new Person(){name="d",age=12,id=4 },
                new Person(){name="e",age=14,id=5 },
                new Person(){name="f",age=12,id=6 },
                new Person(){name="g",age=15,id=7 },
            };
    print_array(list);

    // 1. 方式一
    list.Sort((x, y) =&gt; y.CompareTo(x));
    // 2. 方式二
    list.Sort((x, y) =&gt; x.age &gt; y.age ? -1 : 1);

    print_array(list);

}
</code></pre>
<p>     逆序排序后的输出为</p>
<p><img src="https://files.mdnice.com/user/53424/e34d987c-e27c-4570-b79f-a2f0650a024c.png"></p>
<h2 id="22-使用linq语句进行排序">2.2 使用LINQ语句进行排序</h2>
<p>    接下来介绍一下使用LINQ语句进行排序,LINQ是一组用于C#和Visual Basic语言的扩展。它允许编写C#或者Visual Basic代码以查询数据库相同的方式操作内存数据。在此处我们可以使用两种方式实现:</p>
<ul>
<li>方式一:使用原生的LINQ语句进行查询,此处主要通过自己写LINQ语句;在使用时要注意一点,如果自定义数据继承<code>IComparable&lt;T&gt;</code>接口,那么该数据在比较时会自动调用该数据类的比较方法进行比较,如果未继承该接口,就需要在输入时指定该数据类型使用哪种数据进行比较,如下文代码中,我们使用了<code>d.age</code>属性进行数据比较。</li>
<li>方式二:使用封装好的方法<code>OrderBy()</code>,该方法使用比较简单,可以直接调用对应的方法即可,注意事项跟使用原生的LINQ语句一致。</li>
</ul>
<pre><code class="language-csharp">static void test_person_linq()
{
    List&lt;Person&gt; list = new List&lt;Person&gt;()
            {
                new Person(){name="a",age=15,id=1 },
                new Person(){name="b",age=12,id=2 },
                new Person(){name="c",age=14,id=3 },
                new Person(){name="d",age=12,id=4 },
                new Person(){name="e",age=14,id=5 },
                new Person(){name="f",age=12,id=6 },
                new Person(){name="g",age=15,id=7 },
            };
    print_array(list);
    // 1. 方式一
    IEnumerable&lt;Person&gt; query = from d in list
                              orderby d.age
                              select d;
    // 2. 方式二
    query = list.OrderBy(x =&gt; x.age);
    print_array(query);
}
</code></pre>
<p>如果想进行逆序排序,只需要添加<code>descending</code>关键字进行设定,或者直接使用<code>OrderByDescending()</code> 方法。</p>
<pre><code class="language-csharp">static void test_person_linq_()
{
    List&lt;Person&gt; list = new List&lt;Person&gt;()
            {
                new Person(){name="a",age=15,id=1 },
                new Person(){name="b",age=12,id=2 },
                new Person(){name="c",age=14,id=3 },
                new Person(){name="d",age=12,id=4 },
                new Person(){name="e",age=14,id=5 },
                new Person(){name="f",age=12,id=6 },
                new Person(){name="g",age=15,id=7 },
            };
    print_array(list);
    // 1. 方式一
    IEnumerable&lt;Person&gt; query = from d in list
                              orderby d.age descending
                              select d;
    // 2. 方式二
    query = list.OrderByDescending(x =&gt; x.age);
    print_array(query);
}
</code></pre>
<h2 id="23-多条件排序">2.3 多条件排序</h2>
<p>     在实际使用时,我们可能会遇到多条件排序,即第一个条件相等时时,在采用第二个条件排序,如果遇到这种情况,我们处理起来可能就比较麻烦,对于自定义数据,如果我们在定义数据时继承<code>IComparable&lt;T&gt;</code>接口,并在接口方法中自定义排序要求即可。在下面中我们提供了一种使用<code>Sort()</code>接口并利用委托函数定义比较规则来实现数据排序,代码如下所示:</p>
<pre><code class="language-csharp">static void test_person_sort_more()
{
    List&lt;Person&gt; list = new List&lt;Person&gt;()
            {
                new Person(){name="a",age=15,id=1 },
                new Person(){name="b",age=12,id=2 },
                new Person(){name="c",age=14,id=3 },
                new Person(){name="d",age=12,id=4 },
                new Person(){name="e",age=14,id=5 },
                new Person(){name="f",age=12,id=6 },
                new Person(){name="g",age=15,id=7 },
            };
    print_array(list);
    list.Sort((x, y) =&gt; {
      if (x.age &gt; y.age) { return 1; }
      else if (x.age == y.age)
      {
            if (x.id &gt; y.id) { return 1; }
            else { return -1; }
      }
      else { return -1; }
    });

    print_array(list);

}
</code></pre>
<p>     如果想进行逆序排序,只需要修改一下相关的比较条件即可,逆序排序代码如下所示:</p>
<pre><code class="language-csharp">static void test_person_sort_more_()
{
    List&lt;Person&gt; list = new List&lt;Person&gt;()
            {
                new Person(){name="a",age=15,id=1 },
                new Person(){name="b",age=12,id=2 },
                new Person(){name="c",age=14,id=3 },
                new Person(){name="d",age=12,id=4 },
                new Person(){name="e",age=14,id=5 },
                new Person(){name="f",age=12,id=6 },
                new Person(){name="g",age=15,id=7 },
            };
    print_array(list);
    list.Sort((x, y) =&gt; {
      if (y.age &gt; x.age) { return 1; }
      else if (y.age == x.age)
      {
            if (y.id &gt; x.id) { return 1; }
            else { return -1; }
      }
      else { return -1; }
    });

    print_array(list);
}
</code></pre>
<p>     通过上面代码我们可以看出使用除了可以使用<code>Sort()</code>接口是比较复杂的,其中的比较过程需要我们自己定义。下面我们将介绍使用LINQ语言进行多条件排序,当我们使用原生的LINQ语句时,在进行自定义数据比较时,需要声明所选择的对象的属性,并且按照先后顺序进行排序即可;如果使用封装后的LINQ语句,可以使用<code>OrderBy()</code>以及<code>ThenBy()</code>分别指定条件,在添加条件时,要生命比较的对象属性。代码如下所示:</p>
<pre><code class="language-csharp">static void test_person_linq_more()
{
    List&lt;Person&gt; list = new List&lt;Person&gt;()
            {
                new Person(){name="a",age=15,id=1 },
                new Person(){name="b",age=12,id=2 },
                new Person(){name="c",age=14,id=3 },
                new Person(){name="d",age=12,id=4 },
                new Person(){name="e",age=14,id=5 },
                new Person(){name="f",age=12,id=6 },
                new Person(){name="g",age=15,id=7 },
            };
    print_array(list);
    // 1. 方式一
    IEnumerable&lt;Person&gt; query = from d in list
                              orderby d.age, d.id
                              select d;
    // 2. 方式二
    query = list.OrderBy(x =&gt; x.age).ThenBy(x =&gt; x.id);
    print_array(query);
}
</code></pre>
<p>     如果想进行逆序排序,对于原生LINQ语句,在条件后添加<code>descending</code>即可,对于封装后的LINQ语句,</p>
<pre><code class="language-csharp">static void test_person_linq_more_()
{
    List&lt;Person&gt; list = new List&lt;Person&gt;()
            {
                new Person(){name="a",age=15,id=1 },
                new Person(){name="b",age=12,id=2 },
                new Person(){name="c",age=14,id=3 },
                new Person(){name="d",age=12,id=4 },
                new Person(){name="e",age=14,id=5 },
                new Person(){name="f",age=12,id=6 },
                new Person(){name="g",age=15,id=7 },
            };
    print_array(list);

    // 1. 方式一
    IEnumerable&lt;Person&gt; query = from d in list
                              orderby d.age descending, d.id descending
                              select d;
    // 2. 方式二
    query = list.OrderByDescending(x =&gt; x.age).ThenByDescending(x =&gt; x.id);
    print_array(query);
}
</code></pre>
<p>     自定义数据排序后,程序运行最后输出为:</p>
<p><img src="https://files.mdnice.com/user/53424/fd220eca-b99e-427c-806c-9a30ac1b2772.png"></p>
<p>     自定义数据逆序排序后,程序运行最后输出为:</p>
<p><img src="https://files.mdnice.com/user/53424/ae3eb207-5710-46de-96d9-0f2403457958.png"></p>
<h1 id="3-多维数据排序">3. 多维数据排序</h1>
<p>     在实际应用中,我们可能还会使用到多维数据,例如对于二维数据,我们在排序时可能会按照第二维数据的第一个数据作为主要排序关键字,第二数据作为第二个关键字进行排序,当遇到这种情况时,我们可以直接使用LINQ语句进行排序,如下面代码所示,我们定义了一个二维数组,类似于将一系列点数据存放到数组中,然后我们可以参考上文中自定义数据排序方法,书写排序代码:</p>
<pre><code class="language-csharp">static void test_array_sort()
{
    List&lt;List&lt;int&gt;&gt; list = new List&lt;List&lt;int&gt;&gt;() {
                new List&lt;int&gt;{ 1, 9 } ,
                new List&lt;int&gt;{ 6, 6 } ,
                new List&lt;int&gt;{ 1, 4 } ,
                new List&lt;int&gt;{ 6, 2 } ,
                new List&lt;int&gt;{ 1, 6 } ,
                new List&lt;int&gt;{ 7, 2 } ,
                new List&lt;int&gt;{ 1, 2 } ,
                new List&lt;int&gt;{ 3, 5 }
            };
    print_array(list);
    // 1. 方式一
    IEnumerable&lt;List&lt;int&gt;&gt; query = from d in list
                                 orderby d, d
                                 select d;
    // 2. 方式二
    query = list.OrderBy(x =&gt; x).ThenBy(x =&gt; x);
    print_array(query);
}
</code></pre>
<p>排序后结果输出为:</p>
<p><img src="https://files.mdnice.com/user/53424/80325980-6e99-4651-ada7-882fc22c0fe7.png"></p>
<h1 id="4-总结">4. 总结</h1>
<p>以上就是给大家带来的C#常用排序方式一些实现方式,希望大家在日常使用中能够用到。</p><br><br>
来源:https://www.cnblogs.com/guojin-blogs/p/17938600
頁: [1]
查看完整版本: 【C# 技术】C# 常用排序方式