如何对c#对象进行排序

本文关键字:排序 对象 | 更新日期: 2023-09-27 18:17:52

在我的模型中,我有这个属性的public JObject GenericData { get; set; },我需要在我的控制器中创建Jobject,将数据传递给这个属性。我已经这样做了,但是现在我需要在Jobject中对数据进行排序,我不知道该怎么做。没有针对Jobject的开箱即用排序函数。我在控制器中的代码是这样的:

var attributes = _context.AttributeRecords.Include(a => a.Attribute);
    var queryRecords = attributes.Select(l => new
        {
            RecordId = l.RecordId,
            ProjectId = l.ProjectId,
            Attribute = l.Attribute.Description,
            Value = l.Value,
            InfoId = l.InfoId
        }).ToList();
        var recordsValues = queryRecords.Where(b => b.InfoId == i.InfoId).ToList();
        var jObjectValues = new JObject();
        foreach (var n in recordsValues)
        {
            if (n.Value.Contains(","))
            {
                var stringToSplit = n.Value;
                var stringValues = stringToSplit.Split(',');
                List<string> arr = new List<string>();
                var allValues = "";
                foreach (var d in stringValues)
                {
                    var values = await _context.AttributeValues.FirstOrDefaultAsync(v => v.Key == n.Value);
                    arr.Add(values != null ? values.Description : d);
                    allValues = string.Join(",", arr);
                }
                jObjectValues.Add(n.Attribute, allValues);
            }
            else
            {
                var values = await _context.AttributeValues.FirstOrDefaultAsync(v => v.Key == n.Value);
                jObjectValues.Add(n.Attribute, values != null ? values.Description : n.Value);
            }
            i.GenericData = jObjectValues;
        }

如何对c#对象进行排序

您不需要对Jobject进行排序,您可以这样做:

var queryRecords = attributes.Select(l => new
    {
        RecordId = l.RecordId,
        ProjectId = l.ProjectId,
        Attribute = l.Attribute.Description,
        Value = l.Value,
        InfoId = l.InfoId
    }).OrderBy(o => o.Attribute).ToList();