基于 C# 中另一个浮点列表的排序列表

Sorting List based on another float List in C#

在 C# 中给定以下两个列表:

List<string> X = new List<string>({    "a",    "b",    "c",    "d",    "e",    "f",    "g", "h",  "i"});
List<float>  Y = new List<float> ({ 0.991f, 1.471f, 3.819f, 0.003f, 2.291f, 2.887f, 2.887f,   0, 1.0f});

使用 Y 中的浮点值对 X 进行排序以获得以下输出的 cleanest/shortest 方法是什么?

"h", "d", "a", "i", "b", "e", "f", "g", "c"

具有相同浮点数 "key" 的元素的顺序无关紧要。

这是一种方法:

IEnumerable<string> sorted = X
    .Select((value, index) => new { Index = index, Value = value })
    .OrderBy(o => Y[o.Index])
    .Select(o => o.Value);

基本上:

  • 使用 .Select 将您的列表 (X) 投影到新的匿名对象序列中,其中包含来自 X 的字符串及其在列表中的索引。
  • Order the sequenceY.
  • 中对应的值
  • Select 匿名对象的 Value 部分,用于创建仅包含 X.
  • 中的 string 的新序列

示例: https://dotnetfiddle.net/ZjZvBR

如果每个字符串键都是唯一的并且每个列表都完美匹配,您可以使用 zip from System.Reactive.

将它们用作字典中的键
var dic = X.Zip(Y, (k, v) => new { k, v })
          .ToDictionary(x => x.k, x => x.v);

现在,按值对新形成的字典进行排序。

var sortedDict = from entry in dic orderby entry.Value ascending select entry;

在使用查询语法的 "one-liner" 中,这变成:

var dic = X.Zip(Y, (k, v) => new { k, v })
          .ToDictionary(x => x.k, x => x.v);
          .OrderBy(x => x.Value);

以下代码遵循冒泡排序技术...

for(int i = 1; i < max; i++)
{
    for(int j = 0; j < max - i; j++)
    {
        if(Y[j] > Y[j + 1])
        {
            int temp = X[j];
            X[j] = X[j + 1];
            X[j + 1] = temp;
            int temp1 = Y[j];
            Y[j] = Y[j + 1];
            Y[j + 1] = temp1;
        }
    }
}