c# - 根据优先级数组对字符串数组进行排序

标签 c# .net linq sorting .net-core

我有一个优先列表

List<string> priority = new List<string>() {
              "boss",
              "Project owner",
              "client",
              "manager",
              "client1",
              "client2 ",
              "Intern",
          };

我想根据这个优先级对其他数组进行排序

List<string> arr = new List<string>(){ "client1", "boss", "manager" }
priority.Sort(arr);

它应该返回 ["boss", "manager", "client1"]

注意:可能还有其他项目不在优先级中,因此我们可以将它们放在最后。

最佳答案

优先级列表中,client 1项目显然有一个额外的空间。但是,您可以根据优先级列表中的索引对数组进行排序:

        List<string> priority = new List<string>() {
          "boss",
          "Project owner",
          "client",
          "manager",
          "client1",
          "client2 ",
          "Intern",
      };

     List<string> arr = new List<string>() { "client1", "boss", "manager" };

     var result= arr.OrderBy(x => Array.IndexOf(priority.ToArray(), x)).ToList();

关于c# - 根据优先级数组对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74917757/

相关文章:

c# - 在 .NET 中,为什么 SerialPort.ReadExisting() 返回一个字符串而不是字节数组?

c# - 为什么 Lambda 变量范围存在于 LINQ 查询之外?

c# - NLog 给出异常可能的解释是缺少零参数和单个参数 Common.Logging.Configuration.NameValueCollection 构造函数

c# - 如何识别仍然引用对象实例的位置?

c# - 为什么在匿名方法中不允许使用 out 参数?

c# - 如何使用 WebRequest 访问使用 HTTPS 的 SSL 加密站点?

c# - 将 n-m 关系连接查询转换为 Linq

c# - 如何执行 linq 查询以查找数据集中存在于集合的每条记录中的字段?

c# - Facebook SDK 在 Windows 10 应用程序上加载时出错(XAML、C#)

c# - 带参数的 Dispatcher.BeginInvoke 操作