You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LINQ & C#:按指定规则对含XValue属性的对象列表排序

C# 按指定规则对含XValue属性的对象列表排序

实现思路

  • 先将原始列表按XValue升序排序,保证每次从最小的元素开始筛选
  • 循环处理剩余元素,每次最多选取4个彼此XValue差值≥10的最小元素,加入结果列表后从待处理集合中移除
  • 重复操作直到所有元素都被处理

代码实现

首先定义包含XValue属性的对象类:

public class MyObject
{
    public int XValue { get; set; }
}

然后编写排序方法:

using System;
using System.Collections.Generic;
using System.Linq;

public static class SortHelper
{
    public static List<MyObject> SortByXValueRules(List<MyObject> source)
    {
        // 初始按XValue升序排序
        var remaining = source.OrderBy(o => o.XValue).ToList();
        var result = new List<MyObject>();

        while (remaining.Any())
        {
            var currentBatch = new List<MyObject>();
            int lastSelected = int.MinValue;

            // 遍历剩余元素,筛选符合条件的批次
            foreach (var item in remaining.ToList())
            {
                if (currentBatch.Count >= 4)
                    break;
                
                if (item.XValue - lastSelected >= 10)
                {
                    currentBatch.Add(item);
                    remaining.Remove(item);
                    lastSelected = item.XValue;
                }
            }

            result.AddRange(currentBatch);
        }

        return result;
    }
}

测试示例

// 构造测试数据
var sourceObjects = new List<MyObject>
{
    new MyObject { XValue = 0 },
    new MyObject { XValue = 5 },
    new MyObject { XValue = 10 },
    new MyObject { XValue = 15 },
    new MyObject { XValue = 20 },
    new MyObject { XValue = 25 },
    new MyObject { XValue = 30 },
    new MyObject { XValue = 35 },
    new MyObject { XValue = 40 },
    new MyObject { XValue = 45 },
    new MyObject { XValue = 50 }
};

var sortedList = SortHelper.SortByXValueRules(sourceObjects);

// 输出验证结果:0;10;20;30;5;15;25;35;40;50;45
foreach (var obj in sortedList)
{
    Console.Write($"{obj.XValue};");
}

说明

  • 初始用LINQ的OrderBy完成升序排序,确保筛选逻辑从最小元素开始
  • 每次循环最多选4个元素,严格遵循差值≥10的规则
  • 所有原始元素都会被加入结果列表,不会遗漏

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 14:28:12