【问题标题】:sort and matching the list using linq使用 linq 对列表进行排序和匹配
【发布时间】:2011-11-09 08:31:35
【问题描述】:

我有两个列表。

List A      List B
  a          10
  b           5
  c          20

我必须对 List B 升序进行排序。 在列表 B 的基础上,列表 A 也应该重新排序。所以我的结果会是这样的

List A      List B
 c          20
 a          10
 b          5

我在这里使用 Linq (orderby)。在排序其他列表时面临问题。我该怎么做?

【问题讨论】:

  • 我认为您的结果表明 List B 不是使用 int 而是通过将其视为字符串进行排序的。您采样的排序结果是否正确?

标签: linq


【解决方案1】:

一种方法是

List<string> listA = new List<string> { "a", "b", "c" };
List<int> listB = new List<int> { 10, 5, 20 };

var joined = listA.Select((value, index) => Tuple.Create(value, listB[index]));

List<string> orderedListA = joined.OrderByDescending(t => t.Item2)
                                  .Select(t => t.Item1)
                                  .ToList();

编辑:我错过了 Zip 方法。线

 var joined = listA.Select((value, index) => Tuple.Create(value, listB[index]));

可以写成

 var joined = listA.Zip(listB, (s,i) => Tuple.Create(s,i));

【讨论】:

    【解决方案2】:

    如何使用Zip 运算符:

    List<char> unsortedA = ...
    List<int> unsortedB = ...
    
    var orderedTuples = unsortedA.Zip(unsortedB, Tuple.Create)
                                 .OrderByDescending(tuple => tuple.Item2)
                                 .ToList();
    
    // If required:
    var sortedA = orderedTuples.ConvertAll(tuple => tuple.Item1);
    var sortedB = orderedTuples.ConvertAll(tuple => tuple.Item2);
    

    另一方面,您似乎应该使用元组类型将字符和索引存储在一起,而不是根据索引“关联”它们。

    【讨论】:

      【解决方案3】:

      使用 .Net 4.0 Zip 和匿名类型

      b.Zip(a, (x,y)=>new {Key=x, Value=y}).
        OrderBy(x=>x.Key).
        Select(x=>x.Value).
        ToList()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-01
        • 2010-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多