排序后的动态列表是只读的

本文关键字:只读 列表 动态 排序 | 更新日期: 2023-09-27 18:03:42

我有一个动态列表,我尝试排序,然后根据新的排序顺序更改id:

foreach (Case c in cases)
{
    bool edit = true;
    if (c.IsLocked.HasValue)
        edit = !c.IsLocked.Value;
    eventList.Add(new {
        id = row.ToString(),
        realid = "c" + c.CaseID.ToString(),
        title = c.CaseTitle + "-" + c.Customer.CustomerDescription,
        start = ResolveStartDate(StartDate(c.Schedule.DateFrom.Value.AddSeconds(row))),
        end = ResolveEndDate(StartDate(c.Schedule.DateFrom.Value), c.Schedule.Hours.Value),
        description = c.CaseDescription,
        allDay = false,
        resource = c.Schedule.EmployeID.ToString(),
        editable = edit,
        color = ColorConversion.HexConverter(System.Drawing.Color.FromArgb(c.Color.Value))
    });
    row++;
}
var sortedList = eventList.OrderBy(p => p.title);
for (int i = 0; i < sortedList.Count(); ++i)
{
    sortedList.ElementAt(i).id = i.ToString();
}

但是它在sortedList.ElementAt(i).id = i.ToString();上崩溃了,说它是只读的?

属性或索引器<>f__AnonymousType4<string, string,string,string,string,string,bool,string,bool,string>.id不能被赋值——它是只读的

如何更改id ?

谢谢

排序后的动态列表是只读的

如前所述,您不能更新匿名类型,但是您可以修改流程以使用一个查询,该查询首先对项目进行排序,并将项目的索引作为Select的参数:

var query = cases.OrderBy(c => c.CaseTitle + "-" + c.Customer.CustomerDescription)
                 .Select( (c, i) =>
                    new {
                            id = i.ToString(),
                            realid = "c" + c.CaseID.ToString(),
                            title = c.CaseTitle + "-" + c.Customer.CustomerDescription,
                            start = ResolveStartDate(StartDate(c.Schedule.DateFrom.Value.AddSeconds(i))),
                            end = ResolveEndDate(StartDate(c.Schedule.DateFrom.Value), c.Schedule.Hours.Value),
                            description = c.CaseDescription,
                            allDay = false,
                            resource = c.Schedule.EmployeID.ToString(),
                            editable = c.IsLocked.HasValue ? !c.IsLocked.Value : true ,
                            color = ColorConversion.HexConverter(System.Drawing.Color.FromArgb(c.Color.Value))
                        }
                   );