C# 合并两个int数组 合并后根据大小排序 并输出

 static void Main(string[] args)
        {
            int[] a = new int[] { 1, 3, 4, 8,30,10 };
            int[] b = new int[] { 2, 5, 6, 9, 22,7,11};
            //合并数组
            int[] temp = new int[a.Length + b.Length];
            a.CopyTo(temp, 0);
            b.CopyTo(temp, a.Length);

            #region 方案1 采用冒泡法
            int tNum = 0;//中转值
            string aa = string.Empty;
            for (int i = 0; i < temp.Length; i++)
            {
                for (int j = i + 1; j < temp.Length ; j++)
                {
                    if (temp[j] < temp[i])
                    {
                        tNum = temp[i];
                        temp[i] = temp[j];
                        temp[j] = tNum;
                    }
                }
                aa += temp[i].ToString() + " ";
            }
            Console.WriteLine(aa);
            #endregion

            #region 方案2 使用linq
            string bb = string.Empty;
            var strLinq = from s in temp orderby s select s;//升序排列
            //var strLinq = from s in temp orderby s descending  select s;//降序排列
            foreach (var m in strLinq)
            {
                bb += m.ToString() + " ";
            }
            Console.Write(bb);
            #endregion
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,您需要在C#中使用SQL Server连接字符串连接到您的数据库。然后,您可以使用SQL查询从两个表中获取数据,将结果存储在一个DataTable中。接下来,您可以将DataTable中的数据复制到一个数组中,并使用Array.Sort方法对其进行排序。以下是一个简单的示例代码: ```csharp using System; using System.Data; using System.Data.SqlClient; class Program { static void Main(string[] args) { string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword"; string query = "SELECT * FROM Table1 UNION ALL SELECT * FROM Table2"; SqlDataAdapter adapter = new SqlDataAdapter(query, connectionString); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); // Copy data to array DataRow[] rows = new DataRow[dataTable.Rows.Count]; dataTable.Rows.CopyTo(rows, 0); // Sort array Array.Sort(rows, (a, b) => ((int)a["ID"]).CompareTo((int)b["ID"])); // Print sorted array foreach (DataRow row in rows) { Console.WriteLine(row["ID"] + " " + row["Name"]); } } } ``` 在上面的示例中,我们使用UNION ALL运算符将两个表中的数据合并一个查询中。然后,我们使用SqlDataAdapter将查询结果填充到一个DataTable中。接下来,我们使用DataRow数组将DataTable中的数据复制到一个数组中,并使用Array.Sort方法对其进行排序。最后,我们遍历排序后的数组并打印每一行的ID和Name。请注意,我们使用了一个lambda表达式作为比较器来比较行的ID值。您可以根据需要修改比较器来排序不同的列或以不同的顺序排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值