【问题标题】:C# Sort items in a list, withing the list, that satisfy a conditionC# 对列表中满足条件的项目进行排序
【发布时间】:2015-11-24 13:55:55
【问题描述】:

基本上,我在 C# 中有一个列表,其中包含看起来像这样的结构(代码可能不适合语法)

public struct Numbers {
    public int DistanceFromArbitraryPoint;
    public int X;
    public int Y;
}

我想做的是对列表进行排序:

  1. 按距离排序列表(已经这样做没问题)。
  2. 对于距离

结果是这样的:

Distance 12, x 0, y 0;
Distance 4, x 20, y 20;
Distance 6, x 0, y 3;

第一步之后:

Distance 4, x 20, y 20;
Distance 6, x 0, y 3;
Distance 12, x 0, y 0;

在第 2 步之后(如果距离

Distance 6, x 0, y 3; // lower X and Y Sum, goes first
Distance 4, x 20, y 20;
Distance 12, x 0, y 0; // Distance higher than 10, remains unsorted

【问题讨论】:

  • 您不过滤这三个项目,但这听起来好像您想要这样做:" 对于每个具有距离的数字
  • 另外,"while not create a new list." 是否意味着不允许使用带有final list = query.ToList()的LINQ?
  • 你能分享一下你到目前为止所尝试的吗?让我们不要重复你的努力,除了你应该展示一些研究和失败的尝试。
  • @SimonShine 不适用于 orderby thenby。因为有一个条件。不满足条件的物品应保持不变。

标签: c# linq list sorting


【解决方案1】:

这里需要更复杂的比较方法

var numbers = new List<Numbers>{ new Numbers(6,0,3),   new Numbers(12,0,0), 
                                 new Numbers(4,20,20), new Numbers(5,20,20)};       
int d = 10;

numbers.Sort((a,b)=>
             {
                 if (a.DistanceFromArbitraryPoint >= d && b.DistanceFromArbitraryPoint >= d)                         
                     return a.DistanceFromArbitraryPoint.CompareTo(b.DistanceFromArbitraryPoint);                        
                 if (a.DistanceFromArbitraryPoint >= d)
                     return 1;
                 if (b.DistanceFromArbitraryPoint >= d)
                     return -1;

                 int c = (a.X+a.Y).CompareTo(b.X+b.Y);                       
                 if (c == 0)
                     c = a.DistanceFromArbitraryPoint.CompareTo(b.DistanceFromArbitraryPoint);
                 return c;                       
             });

输出:

6 (0,3); 4 (20,20); 5 (20,20); 12 (0,0)

使用来自List&lt;T&gt;Sort(Comparison&lt;T&gt; comparison),而不是Linq

fiddle

public struct Numbers
{
    public Numbers(int d, int x, int y)
    {
        DistanceFromArbitraryPoint  = d;
        X = x;
        Y = y;
    }
    public int DistanceFromArbitraryPoint;

    public int X;
    public int Y;

    public override string ToString()
    {
        return String.Format("{0} ({1},{2})", DistanceFromArbitraryPoint, X,Y);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多